我想在我的网站中添加加载程序,并且我正在使用 ajaxStart 和 ajxStop 请求来隐藏和显示 div。但问题是 ajaxStart 和 ajaxStop 请求没有被按钮 onclick 触发。 下面是我的代码:
<style>
//css for loader
//another class with overflow=hidden
</style>
现在,我想做的是:
$("#msg1").click(function(event){ //msg1 is the id of the button
$body = $("body");
$.ajaxSetup({'global':true});
$(document).ajaxStart(function(){
$body.addClass("loading");
});
});
但这不起作用。下面的代码有效:
$("#msg1").click(function(event){ //msg1 is the id of the button
alert("Hello");
});
那么,我哪里没捕获要点?
最佳答案
ajaxStart
将在 ajax 请求开始时注册一个处理程序,但它实际上并不触发 ajax 调用。根据您所编写的内容,如果您现在使用任何 jQuery 方法进行 ajax 调用,“loading”类将被添加到 body 标记中。
例如
$( ".result" ).load( "ajax/test.html" );
更新
将您的代码更改为类似的内容以使其正常工作
// Move these out of the click handler as they don't have to run every time
// the button is clicked.
var $body = $("body");
$.ajaxSetup({'global':true});
$(document).ajaxStart(function(){
$body.addClass("loading");
});
$("#msg1").click(function(event){
// Here is where you actually make the ajax call, so the "loading" class
// will now be added to the body tag.
$.ajax( "example.php" )
.done(function(data) {
// Do something with the data you've just retrieved.
// You probably now want to remove the "loading" class too.
})
});
关于javascript - ajaxStart 不适用于 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42880344/