Py学习  »  Jquery

使用jquery,无法添加使用innerhtml创建的单击到按钮的行为

Asderg • 4 年前 • 180 次点击  

我有一些按钮,我用jquery在所有按钮上添加了一些单击行为,它们工作得很好,但是现在这些按钮是通过更改 innerHTM 有脚本的DIV的L,行为不再有效

下面是一个例子,每次我单击这两个按钮中的任何一个,它都会显示一个带有消息的警报 '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>

但是如果我通过改变 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>

我真的不知道发生了什么事

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38114
 
180 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Tibrogargan
Reply   •   1 楼
Tibrogargan    4 年前

$('.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>