我应该将“ajaxStart”方法附加到什么?

时间:2021-05-24 07:12:34

I'd like to check for the presence of any outstanding Ajax events in a script like the following:

我想在如下脚本中检查是否存在未完成的Ajax事件:

$('nav a').click(function(){
    var url = $(this).attr('href');
    $('#content').load(address,function(){
        //do some stuff when complete
    });
});

Now, if the nav is clicked twice, both requests will execute, and I essentially want to prevent this from happening. jQuery offers the .ajaxStart() and .ajaxStop() methods but I don't need to manipulate the DOM so I'm not quite clear on what object to call them on. I was thinking of using a variable instead:

现在,如果导航被点击两次,两个请求都会执行,我本质上想防止这种情况发生。jQuery提供了. ajaxstart()和. ajaxstop()方法,但是我不需要操作DOM,所以我不太清楚调用它们的对象是什么。我想用一个变量代替:

var busy = false;
$(busy).ajaxStart(function(){this=true});
// etc...

With

$('nav a').click(function(){
    if(busy==false){
        var url = $(this).attr('href');
        $('#content').load(address,function(){
            //do some stuff when complete
        });
    }
    else return false;
});

But:

但是:

  1. Is it legal?
  2. 它是合法的吗?
  3. Is there a simpler/more straightforward way of doing this?
  4. 有没有更简单/更直接的方法?

1 个解决方案

#1


3  

The correct way of doing this in javascript is the following:

在javascript中正确的做法是:

(function() {
    var buzy = false;
    $('nav a').click(function(){

        if (buzy) return;
        buzy = true;

        var url = $(this).attr('href');
        $('#content').load(address,function(){
            //do some stuff when complete
            buzy = false;
        });
    });
}());

To answer the original question, ajaxStart could be bound to document:

要回答原始问题,可以将ajaxStart绑定到文档:

$(document).ajaxStart(function() {
    buzy++;
});
$(document).ajaxStop(function() {
    buzy--;
});

#1


3  

The correct way of doing this in javascript is the following:

在javascript中正确的做法是:

(function() {
    var buzy = false;
    $('nav a').click(function(){

        if (buzy) return;
        buzy = true;

        var url = $(this).attr('href');
        $('#content').load(address,function(){
            //do some stuff when complete
            buzy = false;
        });
    });
}());

To answer the original question, ajaxStart could be bound to document:

要回答原始问题,可以将ajaxStart绑定到文档:

$(document).ajaxStart(function() {
    buzy++;
});
$(document).ajaxStop(function() {
    buzy--;
});