我正在構建一個簡單的腳本。我試圖在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
謝謝。我如何維持「這個」的範圍?非常感謝您爲這兩個快速答案。 –