简体   繁体   English

如何停止加载HTML页面的div

[英]How to stop a div loading an HTML page

The remove() on id main is called from clicking another external button. id main上的remove()是通过单击另一个外部按钮来调用的。 The problem is if the user clicks btn1 and quickly presses that external button, the remove is getting called before the event handler for btn1 . 问题是如果用户单击btn1并快速按下该外部按钮,则会在btn1的事件处理程序之前调用btn1 As a result of which the popup is loaded after the div has been removed. 因此,在删除div之后加载弹出窗口。 Is there a way by which the load request can be stopped when event handler for remove is clicked? 有没有一种方法可以在单击删除事件处理程序时停止加载请求? I tried with jqXHR.abort() when remove method is called,but that doesn't work because the remove is called before the ajax is even sent. 我在调用remove方法时尝试使用jqXHR.abort() ,但这不起作用,因为在发送ajax之前调用了remove。

There are many buttons like btn1 which will send ajax requests to load HTML and Few HTMlL files for eg a.html will load some script files like a.js , which will be executed. 有许多按钮,比如btn1,它们会发送ajax请求来加载HTML,而很少有HTMlL文件例如a.html会加载一些像a.js这样的脚本文件,这些文件将被执行。 And if the script refers to some variable which was deleted in remove() , there will be a TypeError. 如果脚本引用了一些在remove()remove()变量,则会出现TypeError。

<div id="base">
    <div id="main">
        <!-- some more HTML elements -->
        <button id="btn1"></button>
    </div>
    <div id ="popup">
    </div>
</div>

<script>  
    var xhr;      
    $("#btn1").on("click", function(){
        xhr = $.ajax(
        url: "a.html",
        success: function(){
             //do something
        }),
        type: "GET"
    });

    $("#main").on("remove", function(){
       // delete all resources,etc.
       xhr.abort();
    });
</script>

Try using a global variable 尝试使用全局变量

var removed = 0;
$('externabutton').click(function(){
  $("#main").remove();
   removed = 1;
});
 $("#btn1").on("click", function(){
        xhr = $.ajax(
        url: "a.html",
        success: function(data){
             if (removed == 0 ) {
              //append the data
             } else {removed ==0;}
        }),
        type: "GET"
    });

As the xhr is async, so we cannot guarantee the xhr is finished before #main.remove method. 由于xhr是异步的,所以我们无法保证xhr#main.remove方法之前完成。 Maybe you could use a flag to control this. 也许你可以使用一个标志来控制它。

var isRemoved = false, xhr;
$("#btn1").on("click", function(){
    if(isRemoved) return;
    xhr = $.ajax({
      url: "a.html",
      success: function(){
           //do something
        if(isRemoved) return;
      },
      type: "GET"
   });
 });

$("#main").on("remove", function(){
   isRemoved = true;
   xhr && xhr.abort();
});

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

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