gpt4 book ai didi

javascript - 在同一个 jquery 函数中,一行在前面的行之前执行

转载 作者:行者123 更新时间:2023-11-30 12:42:49 25 4
gpt4 key购买 nike

这只是一个问题,可以帮助我弄清楚一些基本的东西。

我有一个简单的 html 页面,我在其中放置了 2 个 div:#test 和 #testresult

这个写在单独的 .js 文件中的 JQUERY 很好地包含在 html 页面中

$(document).ready(function () {
var cssleft = $("#test");


(function hhh() {

cssleft.animate({
left: "100px"
}, 3000, function () {
$('#testresult').html(cssleft.css("left"));
}).animate({
left: "-100px"
}, 3000);

cssleft.animate({
width: "100px"
}, 3000).animate({
left: "10px"
}, 3000);

$('#testresult').html(cssleft.css("left"));

})();
});

我不明白的是执行流程。

我原以为这段代码会逐行执行:

1/为 #test div 设置动画,然后在 #testresult div 中写入“左”值 (100px)。2/再次为#test div 设置动画。3/在#testresult div 中写入'left' (10px) 的新值。

但是发生的事情是 1/和 2/只有在 #testresult div 被修改后才会按预期进行: $('#testresult').html(cssleft.css("left")); 好像该行在前两行将 0px 放入 #testresult div 之前被触发。

请问有什么解释吗?

最佳答案

简而言之,animate 是一个异步函数。该行已执行,但代码不会在执行下一行之前等待它完成。

为了在动画完成时执行某些操作,您应该使用此处文档中指示的动画完成函数回调:http://api.jquery.com/animate/

这是您在第一个动画中的代码中所做的。然而,第二个动画没有使用完整的函数来运行该行:$('#testresult').html(cssleft.css("left")); 因此它将立即执行。

关于javascript - 在同一个 jquery 函数中,一行在前面的行之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23796057/

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