【发布时间】:2011-10-12 14:01:00
【问题描述】:
不是一个非常重要的问题,但我们开始吧..
如何避免在 jQuery 事件处理程序中使用 var _this = this? 即我不喜欢这样做:
var _this = this;
$(el).click(function (event) {
//use _this to access the object and $(this) to access dom element
});
以下2种方式都不理想
$(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
【问题讨论】:
-
请解释为什么你认为“event.target 不够好”? jQuery 总是返回自己的格式正确的事件对象,并带有正确的 event.target 值。
-
我一开始就不打字来避免它....
-
当我说“不够好”时,我的意思是:jsfiddle.net/ne3n3 event.target 和 jQuery 在处理程序中为我准备的 this 之间存在差异
标签: javascript jquery syntax