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

标签 javascript php jquery ajax

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>

仅在第一次工作,但当推送重新加载脚本(警报)时不再工作,我可以看到页面加载正常,但脚本没有。

最佳答案

您需要将点击事件委托(delegate)给页面首次运行时存在的事件 -

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

jQuery 仅在运行时识别页面中的元素,因此 jQuery 无法识别添加到 DOM 的新元素。为了对抗这种情况,请使用 event delegation ,冒泡事件从新添加的项目一直到 jQuery 在页面加载时运行时所在的 DOM 中的某个点。许多人使用 document 作为捕获冒泡事件的地方,但没有必要在 DOM 树上走得那么高。理想情况下you should delegate to the nearest parent that exists at the time of page load.

关于javascript - 当按钮从 ajax 调用时,jquery 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28707405/

相关文章:

php - 按下重置按钮后通过关闭旧弹出窗口显示新的弹出窗口并重新显示相同的表单

php - 非对象上的函数bindParam()

php - 如何从缓存中优化ajax或请求

Javascript:为什么这个 JS 停止了?

javascript - ReactJS 中键的意义是什么?

php - 如何使用mysql在两个表上应用搜索

javascript - 事件处理复选框 - jQuery icheck 插件

javascript - kongregate未定义错误javascript

javascript - ES6 Promises 在 catch 之前返回

javascript - 热模块重新加载有什么意义?