理解jQuery中的链接概念很简单,但是在jQuery中遵循链接并不能给出期望的结果。为什么在按钮上单击字体颜色的蓝色而不是红色,然后是蓝色(按链式)??。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
// The following code should make the text-color as red
// and then perform the other chaining function,
// but its not making it red, instead it makes it blue on button click.
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000)
.css("color", "blue")
.slideUp(2000)
.slideDown(2000);
});
});
</script>
</head>
<body>
<p id="p1">jQuery is fun!!</p>
<button>Click me</button>
</body>
</html>上面的jQuery代码应该将文本颜色变成红色,然后执行另一个链接功能,但它不是使其变红,而是使其在单击按钮时变为蓝色。
发布于 2016-04-19 15:28:46
您可以在动画完成后使用回调来执行代码。否则,jQuery将立即尽其所能。链接不像队列那样工作。
$("button").click(function(){
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000, function(){
$(this).css("color", "blue");
})
.slideUp(2000)
.slideDown(2000);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1">jQuery is fun!!</p>
<button>Click me</button>
发布于 2016-04-19 15:28:52
发布于 2016-04-19 15:29:57
您需要将来自slideUp()和slideDown()函数的可用回调函数分别作为文档提到使用。
如果提供,则一旦动画完成,就会触发回调。这对于将不同的动画按顺序排列在一起是有用的。回调不被发送任何参数,但这被设置为动画化的DOM元素。如果多个元素是动画的,那么需要注意的是,回调是每个匹配的元素执行一次,而不是对整个动画执行一次。
因此,您的“链接”方法看起来将与最初的示例有很大的不同:
$("#p1").css('color','red')
.slideUp(2000,function(){
// When the first slide-up has completed, then slide down
$(this).slideDown(2000,function(){
// After you have slid-down, change your color
$(this).css('color','blue');
// Continue down the rabbit hole here...
});
});工作示例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red")
.slideUp(2000, function(){
$(this).slideDown(2000,function(){
$(this).slideDown(2000).css("color", "blue");
})
})
});
});
</script>
</head>
<body>
<p id="p1">jQuery is fun!!</p>
<button>Click me</button>
</body>
</html>
https://stackoverflow.com/questions/36722728
复制相似问题