gpt4 book ai didi

javascript - 防止绑定(bind)到元素父级的函数被触发

转载 作者:行者123 更新时间:2023-11-30 17:36:54 25 4
gpt4 key购买 nike

我有一个无序列表,当用户点击它时,会附加一个包含输入和 anchor 标记的列表项。

然后当用户点击 anchor 时,我想执行一个功能。但是,目前绑定(bind)到无序列表的函数在 anchor 函数之前触发。

示例:

$('ul').on('click', function(e){
console.log('this always fires first even when i only click the <a/>');
// function to create the list item containing the input and link
});

$(document).on('click', 'input, a', function(e){
console.log('this fires second');
e.preventDefault();
e.stopPropagation(); // doesnt seem to do anything, the ul's function still fires
});

我知道我可以通过使用 .off 方法来阻止 ul 的函数触发,但这意味着我每次都必须取消绑定(bind)并重新绑定(bind)。

有没有更好的方法来做到这一点,还是我应该使用 .off 方法?

最佳答案

我认为将输入、a 点击委托(delegate)给文档是罪魁祸首;当它到达那个节点时,ul 上的事件已经被触发。尝试从 ul 本身委托(delegate)第二个事件,并可能使用 stopImmediatePropagation()

无论如何,JSfiddle 上的示例会有所帮助。

关于javascript - 防止绑定(bind)到元素父级的函数被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21853261/

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