创建元素并将事件设置为类时 JQuery 重复事件

JQuery duplicate events when create element and set events to class

本文关键字:事件 JQuery 设置 元素 创建      更新时间:2023-09-26

当我使用 click 事件添加一个项目并存在另一个具有相同类的元素时,该事件是重复的。

$(".add-first").on("click", function() {
  var firstContainer='<div class="second-container"><button class="add-second">add second</button></div>';
  $(this).closest(".first-container").append(firstContainer);
  $(".add-second").on("click", function() {
    $(this).closest(".second-container").append("<br>example");
  });
});
$(".add-second").on("click", function() {
    $(this).closest(".second-container").append("<br>example");
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first-container">
  <button class="add-first">add first</button>
  <div class="second-container"><button class="add-second">add second</button></div>
</div>

然后,当我在每个按钮add second中按一次单击add first此重复事件时,然后当我单击第二个按钮时,它有一些事件,问题是重复事件。

尝试实现事件委托,而不是在每次创建新按钮时绑定事件事件,

$(".add-first").on("click", function() {
  var firstContainer = '<div class="second-container"><button class="add-second">add second</button></div>';
  $(this).closest(".first-container").append(firstContainer);
});
$(".first-container").on("click", ".add-second", function() {
  $(this).closest(".second-container").append("<br>example");
});

演示