简体   繁体   English

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

[英]JS stop working after jquery .load content

Please help me to understand why js stop working after.load THE SAME CONTENT in div.请帮助我理解为什么 js 停止工作 after.load THE SAME CONTENT in 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>

After.load the same content in "reload_div" #make_it_green button stop working? After.load 相同内容在“reload_div”#make_it_green 按钮停止工作? Why?为什么?

When you run your code as you have posted it, the event handler is added to the make_it_green button.当您按照发布的代码运行代码时,事件处理程序将添加到make_it_green按钮。

Once you load the new content with jQuery the element to which the handler was attached no longer exists, so the event handler no longer exists.使用 jQuery 加载新内容后,附加处理程序的元素不再存在,因此事件处理程序不再存在。 You load a new element with the same name, but there's no event handler attached unless you attach the event handler again.您加载了一个具有相同名称的新元素,但没有附加事件处理程序,除非您再次附加事件处理程序。

Alternatively, attach the event handler to the containing div and delegate the event handling.或者,将事件处理程序附加到包含div并委托事件处理。

See this page on MDN for a detailed discussion of event delegation有关事件委托的详细讨论,请参阅 MDN 上的此页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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