Jquery 不会绑定到新的附加元素

Jquery doesn't bind to new appended elements

本文关键字:元素 绑定 Jquery      更新时间:2023-09-26

我发现默认情况下JQuery不绑定新插入的元素。这是一个片段,显示了我试图解释的内容。

http://jsfiddle.net/8hf5r/2/

$('#chg-em').on('click', function(e) {
    $('.local').empty().append('<p id="orange-juice">orange juice<p>');
    e.preventDefault();
});
$("#orange-juice").on('click', function() {
    alert('ola');
});

哪个可能是解决方案?:(谢谢。

使用委托事件:

$(".local").on('click', '#orange-juice', function() {
    alert('ola');
});

在此处了解委托活动:http://api.jquery.com/on/#direct-and-delegated-events