[英]jQuery ajax, wait until beforeSend animation finishes
HTML和CSS:
<a href="#">link</a>
<img src="http://2.bp.blogspot.com/_OIHTbzY7a8I/TOaiTKLqszI/AAAAAAAAAHM/eb3iiOqxzKg/s640/Auto_Audi_Audi_concept_car_005130_.jpg" />
<div></div>
img { display: none; }
a { display: block; }
JS:
$("a").click(function(){
$.ajax({
url: "test.php",
contentType: "html",
beforeSend: function(){
$("img").fadeIn(600, function(){
$("div").append(" | beforeSend finished | ");
});
},
error: function(){
$("div").append(" | error | ");
}
});
return false
});
问题是,在beforeSend
函数完成动画之前, error
函数开始。
这是工作示例http://jsfiddle.net/H4Jtk/2/
error
应该仅在beforeSend
完成时才开始工作。 这个怎么做?
我使用beforeSend
函数在ajax启动时启动块的动画。 我无法删除它。
谢谢。
您可以使用自定义事件等待动画完成,如下所示:
$("a").click(function(){
var img = $("img"),
div = $("div");
$.ajax({
url: "test.php",
contentType: "html",
beforeSend: function(){
img.fadeIn(600, function(){
div.append(" | beforeSend finished | ");
div.trigger("animationComplete");
});
},
error: function(){
if(img.is(':animated')) {
div.one("animationComplete", function() {
div.append(" | error | ");
});
} else {
div.append(" | error | ");
}
}
});
return false
});
笔记:
jQuery.one()
附加一个触发一次的事件处理程序然后被删除。 jQuery.is(':animated')
是jQuery提供的自定义选择器,用于确定元素是否使用jQuery的内置动画方法(例如fadeIn
)进行动画fadeIn
。 新jsFiddle: http : //jsfiddle.net/pgjHx/
在评论中,Happy已经询问如何处理多个动画。 一种方法是向animationComplete
事件处理程序添加一个条件,以查看动画是否正在进行中。 例如:
$("a").click(function(){
var img = $("img"),
div = $("div");
$.ajax({
url: "test.php",
contentType: "html",
beforeSend: function(){
img.fadeIn(600, function(){
div.append(" | beforeSend finished | ");
div.trigger("animationComplete");
});
// Add another animation just to demonstrate waiting for more than one animation
img.animate({
marginTop: '-=5',
opacity: '-=.5'
}, 700, function() {
div.trigger("animationComplete");
});
},
error: function(){
if(img.is(":animated")) {
// Note I've switched to bind, because it shouldn't be unbound
// until all animations complete
div.bind("animationComplete", function() {
if(img.is(":animated")) {
return;
}
div.append(" | error | ");
div.unbind("animationComplete");
});
} else {
div.append(" | error | ");
}
}
});
return false
});
你可以这样做
//在链接点击时运行动画,当动画完成时,//然后启动你的ajax请求。
$("a").click(function () {
$("img").fadeIn(600, function () {
$("div").append(" | beforeSend finished | ");
$.ajax({
url: "test.php",
contentType: "html",
error: function () {
$("div").append(" | error | ");
}
});
return false
});
});
});
问题是,“beforeSend” 完成 -长则退出前的“淡入”结束。 我不知道你想要完成什么,所以很难提供解决方案。 你必须等待启动AJAX操作,直到动画序列(“淡入”) 后,如果你想保证先发生完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.