开发者

To what should I attach the "ajaxStart" method?

开发者 https://www.devze.com 2023-03-29 15:54 出处:网络
I\'d like to check for the presence of any outstanding Ajax events in a script like the following: $(\'nav a\').click(function(){

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

$('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:

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. Is there a simpler/more straightforward way of doing this?


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

(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:

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

精彩评论

暂无评论...
验证码 换一张
取 消