2011-02-10 4 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

+0

@ mwimwi76:ハンドラをトリガするのではなく、.eq(0).addClass( "active")。next()。show(); 'または、クラスを追加するだけで、最初のコンテナを非表示にすることはできません。 $( "。toggle_container")。slice(1).hide(); '*(最初のコンテナ以外のすべてを隠す)*' $( "h6.trigger")click(function(){/*..*/*)eq(0).addClass( 'active'); '*(アクティブなクラスを最初の要素に追加する)* – user113716

+0

awesome!完璧に動作します。ありがとう! – mwimwi76

0

あなただけがマッチした最初のH6に登録され、クリックイベント上げることができる:.ready()が何かをやって古いjqueryの方法ですので、また、それは、代わりに$(document).ready(function(){})の行く

$(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'); 
}); 

をドキュメントロード時。