我正在构建一个简单的脚本。我试图在jQuery中不使用匿名函数,以保持代码清洁。这是代码:TypeError:不是函数
jQuery(function($) {
'use strict';
var Call = {
selection: '',
init: function() {
this.product_opt = $('#product_opt');
this.listenChange();
//this.test();
},
listenChange: function() {
this.product_opt.live('change', this.afterChange);
},
afterChange: function() {
$("#product_opt :checked").each(function() {
this.selection = $(this).attr('value');
console.log(this.selection);
this.ajax_get_cat();
});
},
ajax_get_cat : function(){
return $.ajax({
url: 'http://localhost:8888/mydomain/wp-admin/admin-ajax.php',
data: {
'action': 'show_slider_callback',
'selection': this.selection
},
success: function(data) {
// This outputs the result of the ajax request
//console.log(data);
console.log('returned' + data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
}
};
Call.init();
});
这是HTML:
<div id="product_opt">
<input id="1" class="selector" type="radio" name="group1" value="6" />
<input id="1" class="selector" type="radio" name="group1" value="6" /> </div>
当我尝试使用的形式,这是在控制台返回的错误信息:
TypeError: this.ajax_get_cat is not a function this.ajax_get_cat();
'我试图在jQuery中不使用匿名函数,以便清理代码'一个奇怪的声明,考虑到1)匿名函数没有错,而且它们当然不是'不洁'的,2)你的代码中有很多。另请注意,您在问题结尾处错过了错误。 –
问题是'this',你需要维护范围和上下文。 – Jai
谢谢。我如何维持“这个”的范围?非常感谢您为这两个快速答案。 –