2011-02-10 67 views
2

下面我使用jquery切換顯示div。我需要添加什麼才能讓頁面加載時只有第一個結果處於活動狀態?修改jquery函數

$(document).ready(function(){ 

//Hide (Collapse) the toggle containers on load 
$(".toggle_container").hide(); 

//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state) 
$("h6.trigger").click(function(){ 
    $(this).toggleClass("active").next().slideToggle("slow"); 
    return false; //Prevent the browser jump to the link anchor 
}); 

回答

0

您可以使用eq()(docs)方法或first()(docs)方法從原始選擇中獲得第一個匹配項。

$("h6.trigger").click(function(){ 
    $(this).toggleClass("active").next().slideToggle("slow"); 
    return false; 
}).eq(0).click(); 
// ^------^------grab the first element, and trigger the handler 

或者作爲替代,您可以使用triggerHandler()(docs)方法只觸發第一個。

$("h6.trigger").click(function(){ 
    $(this).toggleClass("active").next().slideToggle("slow"); 
    return false; 
}).triggerHandler('click'); 
// -----^--------this will only trigger the click on the first element. 

這兩個讓你利用原來的DOM選擇,防止需要重新選擇。

+0

有沒有辦法讓第一場比賽動畫?這樣當頁面加載時它已經處於活動狀態 – mwimwi76 2011-02-10 22:08:43

0

你可以只養你匹配的第一個H6註冊的單擊事件:

$(document).ready(function(){ 

//Hide (Collapse) the toggle containers on load 
$(".toggle_container").hide(); 

//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state) 
$("h6.trigger").click(function(){ 
    $(this).toggleClass("active").next().slideToggle("slow"); 
    return false; //Prevent the browser jump to the link anchor 
}); 

$("h6.trigger:first").trigger('click'); 

}); 
0
$(function() { 
$("h6.trigger:first").addClass('active'); 
}); 

同樣,去代替$(document).ready(function(){}),因爲.ready()是做什麼的一個老的jQuery方式在文件加載。