0

我正在使用 JavaScript (Jquery) 尝试按顺序运行一些操作。在我的真实代码中,我有一个运行函数.ready()来启动一些变量。作为此流程的一部分,我从本地存储中读取了一些数据,以删除在先前访问中删除的元素。我删除的元素应用了一个 css 过渡类。当页面第一次加载时,我不希望这些动画出现,所以我要求<body>元素class="fully-loaded"在我的 CSS 中应用,以便过渡工作。fully-loaded只有在我知道所有添加内容并加载其他所有内容之后,我才尝试添加该类。我尝试设置多个.ready()语句,使用队列等来控制顺序或执行。

fully-loaded虽然我认为我已经按顺序运行,但在我运行脚本添加类之前,启动功能似乎并不完整。我正在粘贴我的代码的迷你版本,它表现出同样的问题。我的问题是:init()在运行呼叫之前,如何确保作为启动功能的一部分运行的任何内容都已完成addClass

HTML正文:

<body>
<section id="secA">    <p>Sec A</p>    </section>
<section id="secB">    <p>Sec B</p>    </section>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>    
<script>
//$(document).ready(    Tester.init()   );
//$(document).ready(    $("body").addClass('fully-loaded')  );

//$(document).ready(    Tester.init()   );
$.when(Tester.init()).done(function(){
    $("body").addClass('fully-loaded');
    console.log("Desired Order: 4");
});
</script>    

</body>

另一个文件中的 JavaScript

var Tester = (function() {

    function init() {
        initEvents();
    }

    function initEvents(){       
        console.log("Desired Order: 1");
        setTimeout(
            '$("#secA").remove(); console.log("Desired Order: 2");',
            2000
        );
        console.log("Desired Order: 3");      
    }

    return { init : init };    
})();

CSS 代码

section {   width:200px;   height:200px;     position:absolute;}

#secA   {   background-color:green;     }
#secB   {   background-color:red;       }

section:nth-of-type(1)      {   top: 0;     left: 0;    }
section:nth-of-type(2)      {   top: 0;     left: 50%;  }

.fully-loaded section {
    -webkit-transition: all 2.5s ease-in-out;
    -moz-transition: all 2.5s ease-in-out;
    transition: all 2.5s ease-in-out; 
}

我认为在我的真实代码中,有些东西需要一些时间,就像 setTimeout 一样是异步的。Desired Action: 4发生在Desired Action: 2一般情况下,我如何$("body").addClass('fully-loaded');等到所有开始的事情都Tester.init()完成?

4

0 回答 0