这不是一个非常重要的问题,但是我们开始吧。
如何避免在jQuery事件处理程序中使用var _this = this?
即,我不喜欢这样做:
var _this = this;
$(el).click(function (event) {
//use _this to access the object and $(this) to access dom element
});
以下两种方法都不理想
$(el).click($.proxy(function (event) {
//lost access to the correct dom element, i.e. event.target is not good enough (see http://jsfiddle.net/ne3n3/1/)
}, this));
$(el).click({_this: this}, function (event) {
//have access to $(this) and event.data._this, but it seems too verbose
})
理想情况下,我想做类似的事情
$(el).click(function (event) {
this.method(); // this is accessing the object
event.realTarget; // this is accessing the dom element
}, this); // <= notice this
最佳答案
http://api.jquery.com/event.currentTarget/说:
http://jsfiddle.net/ne3n3/2/
关于javascript - 避免var _this = this;编写jQuery事件处理程序时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7741293/