当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();
});
答案 0 :(得分:6)
也许是因为你在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;
}
});
答案 1 :(得分:3)
你应该看看这个:http://api.jquery.com/jQuery.proxy/还有 - 检查Function.bind原型(ES5规范) - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind或alt方式http://webreflection.blogspot.com/2010/02/functionprototypebind.html
使用that = this
是公平的,但可能不清楚。
jQuery ajax还支持context: this
自动重新绑定回调。