2016-07-20 37 views
1

我對jQuery非常陌生,我處於一個小危機中。點擊打開所有div而不是一個

$(document).ready(function(){ 
    $(".help_box").click(function(){ 
     $(".help_box_answer").toggle(400); 
    }); 
}); 

這裏的class="help_box_answer"設置爲display:none

當我點擊的div的HTML本身

<div class="help_box"> 
    <div class="help_box_title">title box</div> 
     <div class="help_box_answer"> 
      <p>Hidden message</p> 
     </div> 
</div> 

,出現這種情況

enter image description here

回答

5

使用this指到o NLY你與同班點擊,而不是所有的div的元素:

$(document).ready(function(){ 
    $(".help_box").click(function(){ 
     $(this).find(".help_box_answer").toggle(400); 
    }); 
}); 

jsFiddle example

+1

或'$( 「help_box_answer」,這一點).toggle(400);' – Rayon

+2

@Rayon - 是的,他們基本上是等價的。不過,我認爲新用戶往往會被上下文選擇器語法弄糊塗,而使用'.find()'更具可讀性。 – j08691

+1

謝謝,這個訣竅:) – Aberidius

相關問題