gpt4 book ai didi

javascript - JQuery 每个循环在查看其余代码之前都会循环遍历一行代码 x 次

转载 作者:行者123 更新时间:2023-11-28 10:03:59 24 4
gpt4 key购买 nike

我在 Jquery 中有一个循环:

var fadeTime=500;
css_id=0;
$.each(my_array, function (i, d_U) {
css_id++;
an_v=d_U[1];
an_d=d_U[4];

do_c_function("id_344",true,true);

$("#box_"+css_id).fadeIn(fadeTime,function(){

//this stuff will happen once the fadein is complete

$("#box_"+css_id).animate({top: '-50px'},fadeTime,function(){

//this stuff will happen once the animate is complete

alert("#box_"+css_id);//for debugging

});//end of animation

});//end of fadein

});//end of each loop

现在您可能已经注意到,我尝试使用 css_id 变量和 ++; (添加 1)使循环每次都为不同的 div 制作动画每次循环运行时都指向它。

事实是,css_id 在下面的任何代码执行一次之前就达到了很高的值。因此,当需要制作动画时,Jquery 将在应该制作 #box_1 动画时尝试制作 #box_210 动画。

有没有办法让它只执行 css_id++; 行一次,然后执行动画行,然后才再次执行 css_id++; 行.. .等等。

我尝试将 css_id++; 行放入带有两个动画的回调中,但这似乎不起作用。

谢谢

最佳答案

您的动画回调函数正在形成对 css_id 的闭包,因此存储对 css_id 的实时引用,而不仅仅是该变量在动画循环时保存的值创建的。

由于 JavaScript 中所有参数都是按值传递的,因此您可以使用 jQuery 的 data 函数来打破闭包,并对当时的 css_id 值进行快照。

    $("#box_"+css_id).data("css_id", css_id).fadeIn(fadeTime,function(){
var local_css_id = $(this).data("css_id");
$("#box_"+ local_css_id).animate({top: '-50px'},fadeTime,function(){

//this stuff will happen once the animate is complete

alert("#box_" + local_css_id);//for debugging
});//end of animation
});//end of fadein
});//end of each loop

关于javascript - JQuery 每个循环在查看其余代码之前都会循环遍历一行代码 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8651894/

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