jQuery - 在自定义函数中使用 $(this)

发布于 2024-11-09 11:29:21 字数 507 浏览 0 评论 0原文

我正在尝试创建一个自定义函数来解除绑定然后绑定事件。它看起来像这样:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

吃兔兔 2024-11-16 11:29:21

更改:

eventHandler(event);

到:

eventHandler.call(this, event);

这会将函数的“范围”更改为与原始“bind”调用的范围相同。

Change:

eventHandler(event);

To:

eventHandler.call(this, event);

That'll change the "scope" of your function to be the same as the scope of the original "bind" call.

穿透光 2024-11-16 11:29:21

这个怎么样:

App.bindEvent = function(selector, eventType, eventHandler) {
    var element = this;

    $(selector).unbind(eventType);
    $(selector).bind(eventType, function(event) {
        eventHandler.call(element, event);
    });
};

How about this instead:

App.bindEvent = function(selector, eventType, eventHandler) {
    var element = this;

    $(selector).unbind(eventType);
    $(selector).bind(eventType, function(event) {
        eventHandler.call(element, event);
    });
};
寂寞花火° 2024-11-16 11:29:21

您需要调用处理程序在对象的上下文中:

eventHandler.call(this, event);

You need to call the handler in the context of the object:

eventHandler.call(this, event);
笨死的猪 2024-11-16 11:29:21

我认为您正在尝试参考

event.target

例如:

App.bindEvent("#my-element", "click", function(event) {
    var myId = $(event.target).attr("data-my-id");
});

查看 jquery 的事件文档

I think you're trying to refer to

event.target

For example:

App.bindEvent("#my-element", "click", function(event) {
    var myId = $(event.target).attr("data-my-id");
});

check out jquery's event documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文