jQuery触发事件在静态和动态元素上仅触发一次 [英] jquery trigger event only once on static and dynamic elements

查看:80
本文介绍了jQuery触发事件在静态和动态元素上仅触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要触发对特定元素的一次单击即可,该单击可以在页面加载时显示,也可以在以后动态添加.一些代码

i need to trigger only one click on specific element that can be on page load time or added dynamically in the future. Some code

此代码对于在加载时呈现但不会将click事件绑定到动态添加的新元素的元素很好用

This code work just fine for elements that are rendered on load time but wont bind the click event to new elements dynamically added

$(".message-actions .accept").one("click", function(e){
    console.log("accept");
});

另一方面,如果我这样做,它将把事件绑定到新元素,但不要取消绑定事件,因此,如果我再次单击它,它将打印相同的控制台日志

In the other hand if i do it this way, it will bind the event to new elements but don't unbind the event so if i click it again it will print the same console log

$("body").on("click", ".message-actions .accept", function(e){
    console.log("decline");
    $(this).unbind("click");
});

最后,如果我以其他方式执行此操作,则即使在加载或添加了多个元素之后,它也只会在我单击的第一个元素中触发事件.

At last if i do it in this other way it will only fire the event in the first element i click even if there is more than one loaded or added after.

$("body").one("click", ".message-actions .accept", function(e){
    console.log("decline");
});

我该怎么做?

谢谢

推荐答案

您可以将数据添加到用于记住处理程序是否已在之前运行的元素:

You can add data to the element that remembers whether the handler has run before:

$("body").on("click", ".message-actions .accept", function() {
    if (!$(this).data("run-once")) {
        console.log("decline");
        $(this).data("run-once", true); // Remember that we ran already on this element
    }
});

这篇关于jQuery触发事件在静态和动态元素上仅触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆