所以,我有这个:
function foo(){
var that = this;
this.elements = [
$bar = $('.bar'),
$foo = $('.foo')
];
this.example = function(){
alert("a");
}
this.elements.$bar.on('click', that.example);
}
它不起作用,但是如果我更改此行:
this.elements.$bar.on('click', that.example);
对于这个:
this.elements.$bar.on('click', function(){ that.example() });
也就是说,将方法包装成匿名函数,它确实有效......
编辑:如果该方法不在构造函数内,它也可以工作。
最佳答案
我认为您在当前代码中附加方法的方式没有任何问题。虽然我注意到你已经这样调用你的 DOM 元素:
this.elements = [
$bar = $('.bar'),
$foo = $('.foo')
];
this.elements.$bar
相反,尝试将它们分配为对象:
this.elements = {
$bar : $('.bar'),
$foo : $('.foo')
};
然后在您的代码中:
this.elements.$bar.on('click', that.example);
这是一个示例 jsfiddle 以了解更多详细信息: http://jsfiddle.net/b1bsc1rd/
希望对您有帮助
关于javascript - 使用 jQuery 将构造函数方法附加为处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42730700/