gpt4 book ai didi

jQuery .on 点击​​第二次不起作用

转载 作者:行者123 更新时间:2023-12-01 06:35:57 24 4
gpt4 key购买 nike

var elms = $('.selector', list);
elms.off();
elms.on('vclick', function(event, ui) {
event.preventDefault();
var elm = $(this);
customEventHandler(elm, elm.attr("id"));
});

如果我通过 $('.selector', list).on('click',...) 将点击事件绑定(bind)到列表中的元素,则它工作正常。

如果我在执行 .append() 到列表后添加元素并再次调用 $('.selector', list).on('click',...) 没有点击被触发。即使我之前使用 .off() 来删除旧事件。

有什么想法或建议吗?

最佳答案

试试这个方法:- Fiddle

$('.container').on('click', '.selector', function(event, ui) {
event.preventDefault();
var elm = $(this);
alert(elm.index());
});

您可以使用委托(delegate)事件方法来实现此目的。

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

关于jQuery .on 点击​​第二次不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com