2012-01-23 177 views
1

我的問題是獲取第一個tab_content顯示加載。 我的jquery:jquery selector not loading

$(document).ready(function() { 

$(".tab_content").hide(); 
$("ul.tabs").each(function() { 
    $(this).find('li:first').addClass("active"); 
    $(this).next('.tab_container').find('.tab_content:first').show(); 
}); 

我的HTML:

<ul class="tabs"> 
    <li><a href="#tab1">web</a></li> 
    <li><a href="#tab2">graphics/print</a></li> 
    <li><a href="#tab4">img</a></li> 
</ul> 
<div class="gwrapper"> 
    <div id="gallery"> 
     <div id="image"></div> 
     <div id="description">Welcome to my portfolio. Click any link below.</div> 
    </div> 
</div> 

<div class="tab_container"> 
    <div id="tab1" class="tab_content"> 
     content 
    </div> 

,當我提出的UL類= 「標籤」 上面gwrapper(以前是上面tab_container)的問題開始。我知道問題是這條線上的選擇器:

$(this).next('.tab_container').find('.tab_content:first').show(); 

我不知道如何跳轉divs並選擇。我查過它,但我無法將它拼在一起。我不知道是否(或如何)在這裏使用eq()。

實例可以在jpatrolla.com找到(然後單擊組合)

+0

你爲什麼不設置它們是活躍最初是通過你的CSS本身? –

回答

0
$(function() { 
    $(".tab_content").hide(); 
    $(".tabs").each(function() { 
     $(this).find('li').eq(0).addClass("active"); 
     $(this).nextAll('.tab_container').children('.tab_content').eq(0).show(); 
    }); 
}); 

.tabs元素,在您的示例HTML的.tab_container元素是兄弟姐妹,所以你可以使用.siblings().nextAll()從您的.tabs元素中選擇它們。 .siblings().nextAll()之間的區別在於後者僅查找在當前選擇之後出現的元素,而前者查看所有兄弟元素。

請注意,使用.eq(0)而不是:first,它們做同樣的事情,只選擇集合中的第一個元素,但使用.eq()會更快,因爲它不會浪費字符串。

這裏是一個演示:http://jsfiddle.net/YbNJ2/

UPDATE

我通常喜歡幫助別人優化他們的代碼,並儘可能您可以增加通過使用$.each()而不是$().each()甚至b

$(function() { 
    $(".tab_content").hide(); 
    var $tabs = $(".tabs"); 
    for (var i = 0, len = $tabs.length; i < len; i++) { 
     $tabs[i].find('li').eq(0).addClass("active"); 
     $tabs[i].nextAll('.tab_container').children('.tab_content').eq(0).show(); 
    } 
}); 
+0

欣賞jasper的快速反應,感謝您的努力和鏈接!這就是我喜歡stackoverflow的原因。 –

+0

不客氣。我加了一點關於讓你的循環更快的執行。像上面顯示的那樣使用'for'比'.each()'快很多,所以如果你有一些'.tabs'元素,那麼你可能想要改變你的循環。 – Jasper

1

可能:

$(this).siblings('.tab_container').find('.tab_content:first').show(); 

$(this).nextAll('.tab_container').first().find('.tab_content:first').show(); 
+0

你我的朋友是救世主! facepalming自己,因爲.siblings用於腳本的其他部分。 欣賞你的時間詹姆斯!非常感謝! –

0

當您使用。每次當你只是想影響的一件事():埃特你可以使用一個良好的格式化for循環?

$(document).ready(function() { 
    $(".tab_content").hide(); 
    $('.tabs').find('li:first').addClass("active"); 
    $('.tab_container').find('.tab_content:first').show(); 
}); 
0

.next()與剛纔在gwrapper上面移動ul class =「tabs」後的緊隨其後的兄弟不匹配。

如果你接下來要使用,這應該工作,

$(this).next().next('.tab_container').find('.tab_content:first').show();