回调函数触发过早 [英] Callback function fires too early
问题描述
我在 jQuery 中有这个简单的函数:
function detailspage(page) {如果(页面!= checkcurrent){checkcurrent = 页面;$('div#details').children("div").slideUp("slow", function() {$('div#details').children("div"+page).slideDown("slow");});};};
我已经将三个
的 中>,默认情况下它们都向上滑动并看不见.我现在希望在单击每个按钮的按钮时使它们每个向下滑动.当然,打开的 必须首先向上滑动并移出视线,然后才能向下滑动新的.这就是为什么我在上面尝试了这个简单的回调函数.(page
变量包含 div
之一的 id,例如 #info
或 #cast_crew代码>.)
但它不起作用:点击页面底部左侧的三个按钮可以看到错误,命名为演员和工作人员"、信息"和Galleri".
除了似乎不会造成任何延迟的回调函数之外,所有这些都有效.回调无效.我只想在当前框的上滑完成后开始新框的下滑.
怎么了?为什么我的回调不起作用?
谢谢.
解决方案 我会看看 jquery 中的 promise 函数,以确保所有元素都完成了动画:http://api.jquery.com/promise/
例如:
function detailspage(page) {如果(页面!= checkcurrent){//所以我们只需要搜索 dom 一次var details = $('div#details');checkcurrent = 页面;details.children("div").slideUp("slow").promise().done(功能() {$('div' + page).slideDown("slow");});};};
工作示例:http://jsfiddle.net/cm3pv/6/
I have this simple function in jQuery:
function detailspage(page) {
if (page != checkcurrent) {
checkcurrent = page;
$('div#details').children("div").slideUp("slow", function() {
$('div#details').children("div"+page).slideDown("slow");
});
};
};
I have put three <div>
's inside another <div>
called <div id="details">
, and they are all slided up and out of sight by default. I now wish to make each of them slide down, when a button for each of them is clicked. Of course a <div>
that is open must first be slided up and out of sight, before the new one is slided down. That is why I have tried this simple callback function above.
(The page
variable contains an id for one of the div
's, like #info
or #cast_crew
.)
But it doesn't work: You can see the error by clicking the three buttons on the left in the bottom of the page, named "Cast & crew", "Info" and "Galleri".
It all works apart from the callback function that doesn't seem to cause any delay. The callback has no effect. I simply want the slidedown of the new box to start when the slideup of the current box is finished.
What is wrong? Why doesn't my callback work?
Thank you.
解决方案 I would take a look at the promise function in jquery to ensure all elements have completed the animation: http://api.jquery.com/promise/
For your example:
function detailspage(page) {
if (page != checkcurrent) {
// so we only have to search the dom once
var details = $('div#details');
checkcurrent = page;
details.children("div").slideUp("slow").promise().done(
function() {
$('div' + page).slideDown("slow");
});
};
};
Working example: http://jsfiddle.net/cm3pv/6/
这篇关于回调函数触发过早的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文