如何在运行另一个函数之前等待jQuery切换完成? [英] How to wait for a jQuery toggle to finish before running another function?
问题描述
我遗漏了一些确实很明显的东西,但是我无法采用一种方法来等待jQuery切换完成。
I am missing something really obvious but I can't make one of my methods to wait until a jQuery toggle is done.
我有以下三种方法:
const toggleContainer = function() {
addAnswerContainer.toggle("slow");
};
const toggleButtons = function() {
submitAnswerBtn.toggle("slow");
cancelAnswerBtn.toggle("slow");
};
const changeText = function() {
if( addAnswerContainer.is(":hidden") ) {
addOwnAnswerBtn.text("Add your own answer" );
}
else {
addOwnAnswerBtn.text("Hide adding answer");
}
};
我要做的就是让类似的东西起作用:
All I want to do is to have something like this to work:
const toggleUI = function() {
toggleContainer();
toggleButtons();
changeText(); // executes too fast
};
问题是 changeText()
执行太快了,每次检查时, addAnswerContainer.is(:hidden)
返回 false
,除非我 setTimeout
它持续几秒钟,这不是我想要的。我尝试过使用回调以及Promises,但是我无法使其正常工作。如何让 changeText()
等待,直到 addAnswerContainer.toggle()
完成工作? / p>
The problem is that changeText()
executes too quickly and every time it checks, the addAnswerContainer.is(":hidden")
returns false
, unless I setTimeout
it for some seconds, which is not what I want. I tried with callbacks, also with Promises, but I just can't make it work. How can I make the changeText()
to wait, until the addAnswerContainer.toggle()
has done its job?
推荐答案
。 toggle([duration] [,complete])
可选的第二个参数是在动画完成后进行校准的函数,因此只需调用切换
与所需的回调。承诺是执行类似操作的最佳方法:
The optional second argument is the function to cal once the animation is done, so just call toggle
with the desired callback. Promises are the best way to do something like this:
const toggleContainer = () => new Promise(resolve =>
addAnswerContainer.toggle("slow", resolve)
);
const toggleButtons = () => new Promise(resolve => {
submitAnswerBtn.toggle("slow");
cancelAnswerBtn.toggle("slow", resolve);
});
const changeText = function() {
if( addAnswerContainer.is(":hidden") ) {
addOwnAnswerBtn.text("Add your own answer" );
}
else {
addOwnAnswerBtn.text("Hide adding answer");
}
};
然后致电。然后
承诺链异步函数:
Then call .then
on the promises to chain asynchronous functions:
const toggleUI = function() {
toggleContainer()
.then(toggleButtons)
.then(changeText);
};
或者如果您要 toggleContainer
和 toggleButtons
一次运行,并且仅在 changeText
之前等待:
Or if you want toggleContainer
and toggleButtons
to run at once, and only wait before changeText
:
const toggleUI = function() {
toggleContainer()
toggleButtons()
.then(changeText);
};
这篇关于如何在运行另一个函数之前等待jQuery切换完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!