.on() 在 ajax 加载的页面上不起作用

.on() not working on ajax loaded page

本文关键字:不起作用 加载 ajax on      更新时间:2023-09-26

我的软.php代码

<!DOCTYPE html>
<html>
<head><style>
</style>
<script src="jquery.js"></script>
<script>
$(function(){
$("button").on("click",function(){alert("f");});
$("div").on("click",function(){
$("span").load("check.php");
});
});</script></head><body>
<div>Click</div>
<button>eaf</button><span></span>
</body></html>

并检查.php代码

<body>
<button>Hello</button>
</body>

我想在单击通过 ajax 加载的按钮时提醒 f,该按钮在 .live() 中工作正常。但是有人告诉我,.on()可以用来代替live,但.on()在这里不起作用。建议解决方案

$('body').on("click", "button", function(){
    alert("f");
});

由于您的button在页面加载后添加到 DOM,因此您需要使用委托事件。

最好使用其他选择器而不是body.

您可以使用多个选择器,如下所示:

$('body').on("click", "button, div", function(){
    alert("f");
});

阅读有关.on()的信息