2014-02-11 30 views
0

我試圖通過單擊H3標籤來打開和關閉section元素。我已經嘗試了很多選項,無法讓jQuery工作。有人可以發現下面的錯誤嗎?使用jQuery打開和關閉部分查找方法

<div class="sectiondrop"> 
    <h3>Download</h3> 
    <section> 
    <a class="label-en" href="/files/label-eng.pdf" target="_blank"><span></span>Label (ENG)</a> 
      <a class="label-af" href="/files/_label-afr.pdf" target="_blank"><span></span>Label (AFR)</a> 
      <a class="label-msds" href="/files/_ds.pdf" target="_blank"><span></span>DS</a> 
      <a class="label-brochure-1" href="/files/eng.pdf" target="_blank"><span></span>Eng Brochure</a> 
    </section> 
    </div> 




    <div class="sectiondrop"> 
    <h3>Download</h3> 
    <section> 
    <a class="label-en" href="/files/label-eng.pdf" target="_blank"><span></span>Label (ENG)</a> 
      <a class="label-af" href="/files/_label-afr.pdf" target="_blank"><span></span>Label (AFR)</a> 
      <a class="label-msds" href="/files/_ds.pdf" target="_blank"><span></span>DS</a> 
      <a class="label-brochure-1" href="/files/eng.pdf" target="_blank"><span></span>Eng Brochure</a> 
    </section> 
    </div> 


    jQuery(".sectiondrop h3").click(function() { 
     //alert ("hello"); 
     jQuery(".sectiondrop").find('section').toggle("slow"); 
    }); 

回答

3

使用$(this).next()

jQuery(this).next('section').toggle("slow"); 

.siblings()

jQuery(this).siblings('section').toggle("slow"); 

當您的標記是說,h3持有的click的事件沒有一個名爲section所以它從來沒有子女或盛大孩子發現它。

,而不是.find()使用.next().siblings(),因爲它是一個兄弟,其可在相同的水平,你h3是。

並且您還必須在當前上下文中執行此操作,因此請使用$(this)在當前上下文中獲取elem。

+0

他們沒事,但這對我有用,謝謝Jai! – SixfootJames

2

sectionh3元素的下一個兄弟,所以你需要使用.next().find()用於獲取後代元素

jQuery(".sectiondrop h3").click(function() { 
    //alert ("hello"); 
    jQuery(".sectiondrop").next('section').toggle("slow"); 
}); 
+0

謝謝Arun,非常感謝! – SixfootJames

2

使用的.next()來找到部分或nextAll一個更動態的解決方案

jQuery(".sectiondrop h3").click(function() { 
    //alert ("hello"); 
    jQuery(this).next().toggle("slow"); 
}); 

或nextAll

jQuery(".sectiondrop h3").click(function() { 
    //alert ("hello"); 
    jQuery(this).nextAll('section:first').toggle("slow"); 
}); 

DEMO

+1

感謝您的時間安東! – SixfootJames