jQuery - 在自定义函数中使用 $(this)
我正在尝试创建一个自定义函数来解除绑定然后绑定事件。它看起来像这样:
App.bindEvent = function(selector, eventType, eventHandler) {
$(selector).unbind(eventType);
$(selector).bind(eventType, function(event) {
eventHandler(event);
});
};
但是,我面临的问题是我无法使用 this 关键字来引用被单击的 DOM 元素。例如,我不能这样做:
App.bindEvent("#my-element", "click", function() {
var myId = $(this).attr("data-my-id");
});
如何让 this 关键字像 jQuery.bind() 中那样指向单击的 DOM 元素?
感谢您的任何帮助。
I'm trying to create a custom function that unbinds and then binds an event. It looks like this:
App.bindEvent = function(selector, eventType, eventHandler) {
$(selector).unbind(eventType);
$(selector).bind(eventType, function(event) {
eventHandler(event);
});
};
However, the problem I am facing is that I cannot use the this keyword to reference the DOM element that was clicked. For example, I cannot do this:
App.bindEvent("#my-element", "click", function() {
var myId = $(this).attr("data-my-id");
});
How would I go about getting the this keyword to point to the clicked DOM element like it does in jQuery.bind()?
Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更改:
到:
这会将函数的“范围”更改为与原始“bind”调用的范围相同。
Change:
To:
That'll change the "scope" of your function to be the same as the scope of the original "bind" call.
这个怎么样:
How about this instead:
您需要
调用
处理程序在对象的上下文中:You need to
call
the handler in the context of the object:我认为您正在尝试参考
例如:
查看 jquery 的事件文档
I think you're trying to refer to
For example:
check out jquery's event documentation