2011-02-10 159 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方式在文件加载。