当按钮从ajax调用时,jquery不起作用

jquery dont work when button its calling from ajax

本文关键字:jquery 不起作用 调用 按钮 ajax      更新时间:2024-05-23

Page1.php

<span class='Clic_function' aria-hidden='true' id='1'></span>
<span class='Clic_function' aria-hidden='true' id='2'></span>
<span class='Clic_function' aria-hidden='true' id='3'></span>

(我有相同的功能按钮,但不同的ID)

当他们用ajax从页面加载时,不起作用

Page2.php

<html>
<input type="button" id="reload">
<div id="box">
<span class='Clic_function' aria-hidden='true' id='1'></span>
<span class='Clic_function' aria-hidden='true' id='2'></span>
<span class='Clic_function' aria-hidden='true' id='3'></span>
</div>
<script>
    $(".Clic_function").click(function () {
        alert("Hi");
    });
  $("#reload").click(function () {
        $.ajax({
            url: "Page1.php",
            context: document.body,
        }).then(function (result) {
            $("#reload").html(result);
         }
   });
</script>
</html>

只在第一次工作,但当推送重新加载脚本(警报)时不会再次工作,我可以看到页面加载得很好,但脚本号为

您需要将点击事件委托给页面第一次运行时存在的东西-

$(document).on('click', ".Clic_function", function () {
     alert("Hi");
});

jQuery在运行时只知道页面中的元素,因此jQuery无法识别添加到DOM中的新元素。为了解决这种使用事件委派的问题,将事件从新添加的项冒泡到页面加载jQuery时DOM中的某个点。许多人使用document作为捕捉冒泡事件的地方,但没有必要在DOM树上走那么高。理想情况下,您应该委托给页面加载时存在的最近的父级。

您需要使用事件委派并将事件附加到DOM的更高级别。我在示例中将它附加到document

$(document).on('click', '.Click_function', function(){
    alert("Hi");
});