简体   繁体   English

使用 jQuery,无法将点击行为添加到使用 innerHTML 创建的按钮

[英]Using jQuery, can't add behavior on click to buttons created with innerHTML

I have some buttons and I added some behavior on click to all of them with jQuery and they worked fine, but now that those buttons are generated dynamically by changing the innerHTM L of the div with a script, the behavior don't work anymore我有一些按钮,我使用 jQuery 在所有按钮上添加了一些点击行为,它们工作正常,但是现在这些按钮是通过使用脚本更改 div 的innerHTM L 动态生成的,该行为不再起作用

Here is an example, like this every time I click any of the two buttons, it show an alert with the message 'clicked' .这是一个例子,每次我点击两个按钮中的任何一个时,它都会显示一个带有'clicked'消息的警报。

Fiddle小提琴

 $('.foo').on('click', function(){ alert('clicked'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="home"> <button class='foo' > Test </button> <button class='foo' > Test </button> </div>

But if I insert the buttons by changing the innerHTML of home with the button generate, it does not works anymore但是,如果我通过使用按钮生成更改 home 的innerHTML来插入按钮,则它不再起作用

Fiddle小提琴

 $(".gen").on("click", function(){ $('.home').html( "<button class='foo' > Test </button>" + "<button class='foo' > Test </button>"); }) $('.foo').on('click', function(){ alert('clicked'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <button class="gen" > Generate </button> </div> <div class="home"> </div>

I really don't know what's going on我真的不知道发生了什么

$('.foo') selects certain elements. $('.foo')选择某些元素。 .on() adds an event handler to only the selected elements. .on()仅向所选元素添加事件处理程序。 Any new elements with the "foo" class will not have that handler.具有“foo”类的任何新元素都不会具有该处理程序。 Either add them manually to the new elements or better still use a delegate.要么手动将它们添加到新元素,要么最好仍然使用委托。

Basically, since your "foo" elements do not exist until after you click "generate", the call to .on() adds a handler to nothing.基本上,由于您的“foo”元素直到您单击“generate”后才存在,因此对.on()的调用会将处理程序添加到任何内容。

Here's a solution using jQuery's delegate implementation这是使用 jQuery 的委托实现的解决方案

 $(".gen").on("click", function(){ $('.home').html( "<button class='foo' > Test </button>" + "<button class='foo' > Test </button>"); }) $(document).on('click', '.foo', function(){ console.log('clicked'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <button class="gen" > Generate </button> </div> <div class="home"> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM