var obj = {
someFunction : function() {
$('#someID').on('change', '#someOtherId', function(e) {
this.someOtherFunction(); // works fine
}.bind(this));
},
someOtherFunction : function() {
// do something
}
}
上面的代码工作正常,但我不确定如何使用$(this)
中的someFunction
访问jQuery包装元素。感谢帮助。
答案 0 :(得分:4)
var obj = {
someFunction : function() {
var me = this;
$('#someID').on('change', '#someOtherId', function(e) {
var $elem = $(this); // element / jquery object
me.someOtherFunction(); // works fine
// me is assigned in "obj" scope
});
},
someOtherFunction : function() {
// do something
}
}
答案 1 :(得分:2)
我认为干净的方法是使用$.proxy
var obj = {
someFunction : function() {
$('#someID').on('change', '#someOtherId', $.proxy(this.someOtherFunction, this));
},
someOtherFunction : function(e) {
//this is the jquery $(this) element
var $el = $(e.currentTarget);
//the "this" is the main "obj" object
}
}
在匿名回调函数上:
var obj = {
someFunction : function() {
$('#someID').on('change', '#someOtherId', $.proxy(function (e) {
//this is the jquery $(this) element
var $el = $(e.currentTarget);
//the "this" is the main "obj" object
this.someOtherFunction();
}, this));
},
someOtherFunction : function(e) {
}
}