gpt4 book ai didi

javascript - 变量范围帮助 : this. reset() 不是函数

转载 作者:行者123 更新时间:2023-11-30 07:18:35 26 4
gpt4 key购买 nike

当 save() 执行 this.reset() 或 that.reset() 时,它找不到 reset() 方法并说它不是函数。我在 init() 上使用了一个变通方法来让它工作,但是那个方法在 save() 中不起作用

var vehicle = function () {
return {
init: function () {
var that = this;

jQuery('.vehicle-year-profile .options .delete').bind('click', function (e) {
e.preventDefault();
that.remove(jQuery(e.currentTarget).parents('.vehicle-year-profile'));
});

jQuery('.vehicle-year-profile .options .edit').bind('click', function (e) {
e.preventDefault();
that.edit(jQuery(e.currentTarget).parents('.vehicle-year-profile').attr('id'));
});

jQuery('#association-detail .save').bind('click', function (e) {
e.preventDefault();
that.save();
});
},
save: function () {
var data = new Array();
data['onSet'] = '';
var onSet = jQuery('#association-detail input:checked');
for (var i = 0; i < (onSet.length-1); i++) {
data['onSet'] = data['onSet']+','+onSet.attr('id');
}

var priceSet = jQuery('#association-detail input[type=text]');
for (var i = 0; i < (priceSet.length-1); i++) {
data['priceSet'] = data['priceSet']+','+priceSet.attr('id')+':'+priceSet.val();
}

jQuery.ajax({
type: 'post',
url: '/ajax/store/product/saveAssocDetail.php',
data: data,
success: function (r) {
if (r.length > 0) {
document.triggerNotification('check', 'Changes have been saved');
var that = this;
that.reset(); //ERROR IS TRIGGERED HERE
} else {
document.triggerNotification('x', 'Unable to save changes');
}
},
error: function () {
document.triggerNotification('x', 'Unable to process your request, ajax file not found');
return false;
}
});
},
reset: function () {
jQuery('#association-detail h3').html('');
jQuery('#assocationVehicleId').val('');

jQuery('#association-detail input:checked').attr('checked', false);
jQuery('#association-detail input[type=text]').val('0.00');

jQuery('#association-detail').hide();
}
}
}();
jQuery(function() {
vehicle.init();
});

最佳答案

可能是因为您在 ajax 调用中引用了 this。尝试放置这一行:

var that = this;

在进行 ajax 调用之前,然后在 ajax 调用中明确引用 that。所以,像这样:

var that = this;

jQuery.ajax({
type: 'post',
url: '/ajax/store/product/saveAssocDetail.php',
data: data,
success: function (r) {
if (r.length > 0) {
document.triggerNotification('check', 'Changes have been saved');

/**
* now you can refer to "that", which is in the proper scope
*/

that.reset(); //ERROR IS TRIGGERED HERE
} else {
document.triggerNotification('x', 'Unable to save changes');
}
},
error: function () {
document.triggerNotification('x', 'Unable to process your request, ajax file not found');
return false;
}
});

关于javascript - 变量范围帮助 : this. reset() 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3763320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com