gpt4 book ai didi

javascript - 试图用 $.on(..) 替换 $.live(..)

转载 作者:行者123 更新时间:2023-11-30 08:11:26 24 4
gpt4 key购买 nike

我一直在阅读有关用 on() 替换 jQuery live() 函数的内容,但它们的工作方式与非实时函数相同。

例如,使用 $('a').on('click', function(){}); 与使用:$('a' ).click(函数(){});

我需要复制 $('a').live('click', function(){}); 的功能因为我正在向页面动态添加元素。

最佳答案

您需要提供一个选择器:

$('#container').on('click', 'a', function(){})

#container 是所有相关 anchor 的 static 父级的 id
尝试将 on 附加到最近的静态父级。

开启 docs :

if selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

关于javascript - 试图用 $.on(..) 替换 $.live(..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794661/

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