我只需要触发一次特定元素的点击,这些元素可以在页面加载时出现,也可以在将来动态添加。一些代码
此代码适用于在加载时呈现但不会将点击事件绑定(bind)到动态添加的新元素的元素
$(".message-actions .accept").one("click", function(e){
console.log("accept");
});
另一方面,如果我这样做,它会将事件绑定(bind)到新元素但不会取消绑定(bind)事件,所以如果我再次单击它,它将打印相同的控制台日志
$("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
}
});
关于javascript - jquery 仅在静态和动态元素上触发事件一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25576221/