私信  •  关注

Tibrogargan

Tibrogargan 最近创建的主题
Tibrogargan 最近回复了
4 年前
回复了 Tibrogargan 创建的主题 » 使用jquery,无法添加使用innerhtml创建的单击到按钮的行为

$('.foo') 选择某些元素。 .on() 仅向所选元素添加事件处理程序。任何具有“foo”类的新元素都不会具有该处理程序。或者手动将它们添加到新元素中,或者最好还是使用委托。

基本上,由于您的“foo”元素在单击“generate”之后才存在,因此调用 () 不向任何内容添加处理程序。

下面是一个使用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>