JS在jquery.load内容后停止工作



请帮助我理解为什么js在加载div.中的相同内容后停止工作

<main class="container">
<div id="reload_div">
<div id="color_div" style="width:100px;height:100px; background:red; margin-bottom: 100px">
orig
</div>
<button id="make_it_green" type="submit" class="btn btn-sm btn-primary">
make it green
</button>
</div>
<button id="reload_btn" type="submit" class="btn btn-sm btn-primary" style="margin-top:20px">
reload
</button>
</main>
<script>
$("#make_it_green").click(function(){
$("#color_div").css("background","green")
}); 
$("#reload_btn").click(function(){
$("#reload_div").fadeTo(300,0, function () {
$("#reload_div").load ("reload.php", 
{  }, function () {
$("#reload_div").fadeTo(300,1, function () {
});
});
});
}); 
</script>

在"加载"中加载相同的内容之后;reload_div"#make_it_green按钮停止工作!为什么?

当您在发布代码时运行代码时,事件处理程序会添加到make_it_green按钮中。

使用jQuery加载新内容后,处理程序所附加的元素将不复存在,因此事件处理程序也不复存在。您加载了一个同名的新元素,但除非再次附加事件处理程序,否则不会附加任何事件处理程序。

或者,将事件处理程序附加到包含的div并委托事件处理。

$("#reload_div").click(function(e){
e.preventDefault();
// Check the id of the original target element. If it's 
// our button, change the colour.
if (e.target.id === "make_it_green") {
$("#color_div").css("background", "green");
}
});

有关活动授权的详细讨论,请参阅MDN上的此页面

最新更新