使用 jQuery 向动态添加的元素添加事件侦听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12065329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:16:07  来源:igfitidea点击:

Adding event listeners to dynamically added elements using jQuery

jqueryevents

提问by Wiz

So right now, I understand that in order to attach an event listenerto a dynamicallyadded element, you have to redefine the listener after adding the element.

所以现在,我明白为了将事件侦听器附加到动态添加的元素,您必须在添加元素后重新定义侦听器。

Is there any way to bypass this, so you don't have to execute a whole extra block of code?

有没有办法绕过这个,这样你就不必执行整个额外的代码块?

回答by Hyman

Using .on()you can define your function once, and it will execute for any dynamically added elements.

使用.on()你可以定义你的函数一次,它会为任何动态添加的元素执行。

for example

例如

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something
});

回答by zerkms

$(document).on('click', 'selector', handler);

Where clickis an event name, and handleris an event handler, like reference to a function or anonymous function function() {}

其中click是事件名称,handler是事件处理程序,如对函数或匿名函数的引用function() {}

PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document.

PS:如果您知道要向其添加动态元素的特定节点 - 您可以指定它而不是document.

回答by Luc Kim-Hall

You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.

您正在动态生成这些元素,因此在页面加载时应用的任何侦听器都将不可用。我已经用正确的解决方案编辑了你的小提琴。基本上,jQuery 通过将事件附加到父元素并将其向下传播到正确的动态创建的元素来保存事件以供以后绑定。

$('#musics').on('change', '#want',function(e) {
    $(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
    var ans=$(this).val();
    console.log(($('#want').is(':checked')));
});

http://jsfiddle.net/swoogie/1rkhn7ek/39/

http://jsfiddle.net/swoogie/1rkhn7ek/39/

回答by haotang

When adding new element with jquery plugin calls, you can do like the following:

使用 jquery 插件调用添加新元素时,您可以执行以下操作:

$('<div>...</div>').hoverCard(function(){...}).appendTo(...)