JQuery 未检测到附加项目[重复]

问题描述 投票:0回答:1

大家好

当我遇到这个错误时,我已经在 JQuery Web 项目上工作了一段时间:

index.html

<body>
  <div id="target">
    <h1>Will be called</h1>
  </div>
  <button>Add h1</button>
  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</body>

index.js

$(document).ready(function() {
  $("button").click(function() {
    $("#target").append(`<h1>` + "Will not be called" + `</h1>`);
  });
});

$("#target h1").click(function() {
  alert("clicked");
})

现在的问题是,如果附加了一个元素,即使明确编写了该元素,JQuery 也不会对其进行计数。

如果单击硬写的 h1,则会出现警告,但如果单击附加的,则不会发生这种情况。在我的项目中,我需要两个元素以相同的方式运行,无论它们是否附加。

javascript html jquery append
1个回答
-1
投票

使用事件委托。

$("#target").on("click", "h1", function() {
      alert("clicked");
    })

演示:

$(document).ready(function() {
  $("button").click(function() {
    $("#target").append(`<h1>` + "Will not be called" + `</h1>`);
  });
});

//use event delegation
//parent on click in child...
$("#target").on("click", "h1", function() {
  alert("clicked");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <div id="target">
    <h1>Will be called</h1>
  </div>
  <button>Add h1</button>

© www.soinside.com 2019 - 2024. All rights reserved.