点击事件不会在jquery中触发

我添加了一个新元素但是当我点击它时它没有响应。

HTML

 

使用Javascript

 $(function(){ $('button').click(function(){ $('div').append('x'); }); $('.x').click(function(){ alert('fire'); }); }); 

 $(function() { $('button').click(function() { $('div').append('x'); }); $('div').on('click', '.x', function() { alert('fire'); }); }); 
   

当元素不存在于文档中时,无法通过调用$(".x")将单击事件绑定到动态生成的元素。 其中一个解决方案是使用事件委派,类似于

 $(document).on("click",".x",function(){ // do your work here }) 

另一种方法是在生成元素时将click事件绑定到元素

 $('button').click(function(){ $('div').append($("",{ class: x }).text("x").click(function(){ // do your work here })); }); 

您在x类存在的项之前添加事件侦听器。 您希望在追加该范围后立即添加该事件侦听器。

 $(function(){ $('button').click(function(){ $('div').append('x'); $('.x').click(function(){ alert('fire'); }); }); 

});

您无法将事件直接绑定到jQuery中动态创建的元素。

使用event-delegation绑定到动态创建的元素的父级:

 $(function(){ $('button').click(function(){ $('div').append('x'); }); $('button').on("click", ".x", (function(){ alert('fire'); }); }); 

有关此内容的更多信息,请访问: http : //api.jquery.com/on/