gpt4 book ai didi

javascript - 避免 var _this = this;在编写 jQuery 事件处理程序时

转载 作者:数据小太阳 更新时间:2023-10-29 05:27:15 26 4
gpt4 key购买 nike

这不是一个非常重要的问题,但我们开始吧..

如何避免在 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

最佳答案

http://api.jquery.com/event.currentTarget/说:

"This property will typically be equal to the this of the function."

http://jsfiddle.net/ne3n3/2/

关于javascript - 避免 var _this = this;在编写 jQuery 事件处理程序时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7741293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com