jquery只在静态和动态元素上触发一次事件

jquery trigger event only once on static and dynamic elements

本文关键字:事件 一次 静态 元素 动态 jquery      更新时间:2023-09-26

我只需要在页面加载时或将来动态添加的特定元素上触发一次单击。某些代码

这段代码适用于加载时呈现的元素,但不会将点击事件绑定到动态添加的新元素

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

另一方面,如果我这样做,它会将事件绑定到新元素,但不会解除绑定,所以如果我再次单击它,它会打印相同的控制台日志

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

最后,如果我用另一种方式来做,它只会在我点击的第一个元素中触发事件,即使之后加载或添加了多个。

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

我该怎么做?

感谢

您可以将数据添加到元素中,以记住处理程序以前是否运行过:

$("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
    }
});

我会这样做:

 var handleClick = function () {
     // do your work
     alert("decline");
     // unbind
     $("body").off("click", ".message-actions .accept", handleClick);
 };
 $("body").on("click", ".message-actions .accept", handleClick);

检查此小提琴

如果适合您的情况,您可以这样解决:http://jsfiddle.net/hu4fp5qs/1/

$("body").on("click",".message-actions .accept",function(){
    $(this).removeClass("accept").addClass("decline");
    alert("Declined");
});

单击移除类accept并添加类decline

这将帮助你以不同的方式设计两种情况,以便区分它们。

.accept{
    background-color:green;
}
.decline{
    background-color:red;
}