gpt4 book ai didi

javascript - jQuery:为什么不在生成的按钮上调用点击功能

转载 作者:行者123 更新时间:2023-11-28 04:22:55 24 4
gpt4 key购买 nike

这是一个jsFiddle解释我的问题。如果您尝试单击“添加成分”按钮,则会调用按钮单击事件。我的问题是,当我点击“创建字幕”时,它会为每个子类别动态创建“添加成分”按钮。所有按钮都具有相同的 ID,以“create-ingredient”开头并与唯一 ID 连接,因此它为按钮创建了一个唯一 ID。然后,我在 jQuery 中使用“开始于”选择器来选择所有以“create-ingredient”开始的按钮。它只是不选择那些动态创建的,它只与最初在 html 页面中的那些一起工作。

这里是点击事件没有触发动态的:

$("[name^='create-ingredient']").click(function() {
alert('ingredient clicked');
return false;
});​

我需要更改什么才能调用动态创建的按钮事件?

谢谢!

最佳答案

click静态连接事件。你要on ,即使在添加的元素上也会触发事件。

请注意,on 的语法与 click 略有不同。您通常使用:

$("container").on("click", "selector", handler);

其中“container”选择一个静态容器元素(可以是“document”),而“selector”是您要定位的元素。

Forked Fiddle.


编辑

根据 David 的评论澄清以上内容:on 的使用实际上将事件处理程序附加到“容器”,并将回调委托(delegate)给容器内与“选择器”匹配的任何元素。这是一个非常值得阅读 JQuery docs 的案例:

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 - jQuery:为什么不在生成的按钮上调用点击功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13831452/

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