简体   繁体   中英

.on() not working on ajax loaded page

My soft.php code

<!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>

And check.php code

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

I want to alert f on clicking on button which is loaded via ajax which was working fine with .live(). But someone told me that .on() can be used in place of live but .on() is not working here.Suggest Solution

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

As your button added to DOM after page load you need to use delegate event.

It would be better to use something other selector instead of body .

You can use multiple selector like follwoing:

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

Read about .on()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM