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/