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

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

有没有什么办法可以绕过这个问题,这样就不用执行额外的代码块了?

141217 次浏览
$(document).on('click', 'selector', handler);

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

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

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

for example

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

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

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

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.

$('#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/