gpt4 book ai didi

javascript - 我如何让 jQuery 在 .each() 循环完成之前将效果应用于每个项目?

转载 作者:行者123 更新时间:2023-11-30 18:52:29 27 4
gpt4 key购买 nike

我有以下列表:

<div id="test">test</div>

<ul>
<li>foo</li>
<li>bar</li>
<li>sta</li>
<li>cko</li>
</ul>

和以下 jQuery 代码:

$(document).ready(function() {
$('li').each(function(index) {
$('#test').text($(this).text());
$('#test').show("drop", { direction: "down" }, 500, function() {
$("#test").delay(1000).hide("puff", {}, 100);
});
});
});

从逻辑上讲,这应该将 div test 的内容更改为 foo,应用 drop and puff 效果,将内容更改为 bar,应用效果,等等。但是当您运行它时,整个 .each 循环会在效果开始之前结束,因此最后一个元素 cko 会首先出现并进行 4 次动画处理。

我怎样才能让每一项都得到效果,然后继续进行下一项?

最佳答案

如果您希望它按队列的顺序发生,您还需要在队列中添加第一个函数(使用 .queue() ),如下所示:

$(function() {
$('li').each(function(index) {
var li = $(this);
$('#test').queue(function(n) {
$(this).text(li.text()); //set the text
n(); //call next function in the queue
}).show("drop", { direction: "down" }, 500, function() {
$(this).delay(1000).hide("puff", {}, 100);
});
});
});​

You can give it a try here .这会将文本设置排队与动画顺序发生,这似乎是您所追求的。调用传递给您的队列回调的函数很重要,因为它会推进队列,在这种情况下触发后面的动画。

.delay()也会以您的方式产生奇怪的效果,如果您希望它在队列中,请这样做:

$(function() {
$('li').each(function(index) {
var li = $(this);
$('#test').queue(function(n) {
$(this).text(li.text());
n();
}).show("drop", { direction: "down" }, 500)
.delay(1000).hide("puff", {}, 100);
});
});​

You can try it here ,这实际上会在继续之前为每个元素暂停一秒钟。

关于javascript - 我如何让 jQuery 在 .each() 循环完成之前将效果应用于每个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3343550/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com