To what should I attach the "ajaxStart" method?
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:
- Is it legal?
- 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--;
});
精彩评论