jQuery,等待方法完成然后触发一个动作

问题描述 投票:0回答:1

这是我的情况。我需要先运行此方法

$(editor.image.toggleCaption);

然后:

alert('hello world');

如果我这样做:

$(editor.image.toggleCaption);
alert('hello world');

它不起作用,因为在方法完成之前触发了alert

我能让它工作的唯一方法是使用setTimeout。但这是一个静态的解决方案,所以我想避免它。我尝试了$.Deferred,但我不知道如何设置它,我尝试的所有组合都没有用。

有人能帮我吗?

提前致谢

jquery promise
1个回答
1
投票

使用when,这似乎work.ref https://api.jquery.com/jquery.when/。用你的function.hope替换$('.test').hide('slow')这有助于

$.when($('.test').hide('slow')).then(function(){
    alert(1);
})  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">Some Contents</div>
© www.soinside.com 2019 - 2024. All rights reserved.