2011-08-17 47 views
0

我正在使用一些jQuery代碼來創建頁面的內容分解成(從標籤塊的頂部可導航)的標籤,並期待執行以下操作時,「下一個「或‘以前’鏈接(放置在每個選項卡的內容的底部)被點擊:使用setTimeout與jQuery的問題排序功能

  1. 的頁面向上滾動到標籤塊的頂部(使用成功地實施」 .scrollTo」插件)上爲750ms
  2. 一旦滾動,選項卡將更改爲相應的「上一個」或「下一個」選項卡(由hashtag url標識) - 250ms之後。

使用下面的代碼:

$(".external_link").click(function() { 
$.scrollTo(515, 750, {easing:'easeInOutQuad'}); 
setTimeout(changeTab($(this).attr("href")), 1000); 
return false; 
}); 

兩個發生在在莫同一時間。如果有人能夠說明我做錯了什麼,我會非常感激。

完全代碼:

$(document).ready(function() { 

$(".tab_content").hide(); 
$("ul.content_tabs li:first").addClass("active").show(); 
$(".tab_content:first").show(); 

$('.content_tabs li').each(function(i) { 
var thisId = $(this).find("a").attr("href"); 
thisId = thisId.substring(1,thisId.length) + '_top'; 
$(this).attr("id",thisId); 
}); 

function changeTab(activeTab) { 

$("ul.content_tabs li").removeClass("active"); 
$(activeTab + '_top').addClass("active"); 

$(".tab_content").hide(); 
$(activeTab).fadeIn(); 

} 

//check to see if a tab is called onload 
if (location.hash!=""){changeTab(location.hash);} 
//if you call the page and want to show a tab other than the first, for instance  index.html#tab4 

$("ul.content_tabs li").click(function() { 
if ($(this).hasClass("active")) 
return false; 

changeTab($(this).find("a").attr("href")); 
return false; 
}); 


$(".external_link").click(function() { 
$.scrollTo(515, 750, {easing:'easeInOutQuad'}); 
setTimeout(changeTab($(this).attr("href")), 1000); 
return false; 
}); 
}); 

我說得對不對要嘗試與setTimeout的做到這一點?我的知識非常有限。

回答

1
setTimeout(changeTab($(this).attr("href")), 1000); 

這是錯誤的,你必須放入一個函數,而不是執行函數的結果,250毫秒更有意義。 changeTab是一個函數,changeTab(參數)正在執行一個函數。因此,嘗試

var that = $(this); 
setTimeout(function() {changeTab(that.attr("href"))}, 250); 

我認爲他們在同一時間執行的原因是因爲你直接調用changeTab功能,當您設置超時,併爲750毫秒過程使用之前,先前的功能等待。

+0

完美!非常感謝! :) –

1

您正在傳遞函數請致電setTimeout()。您需要傳遞函數參考。該調用會立即執行,但是當超時到期時將執行函數引用。呼叫setTimeout()這樣的:

setTimeout(function() { changeTab($(this).attr("href")); }, 1000); 

此外,你應該考慮其指示功能.scrollTo() pluginonAfter選項的優勢完成滾動時調用。它可能會更有意義去:

$.scrollTo(515, 750, { 
    easing: 'easeInOutQuad', 
    onAfter: function() { 
     setTimeout(function() { changeTab($(this).attr("href")); }, 250); 
    } 
}); 
+0

非常感謝您的解釋! –