2011-09-10 32 views
3

我有這樣的HTML代碼:jQuery的孩子>父>子

<div class="im"> 
<div style="height:220px">HELLO WORLD! 
<a class="close">X</a> 
<a class="open" style="display:none;">V</a> 
</div> 
</div> 

<div class="im"> 
<div style="height:220px">HELLO WORLD! 
<a class="close">X</a> 
<a class="open" style="display:none;">V</a> 
</div> 
</div> 

,我想按X(類接近)更改父DIV的高度爲20px,並顯示V(類開放),但分別用類im隱藏每個div中的X(class close)。然後按V(class open)將父div的高度更改爲220px並顯示X,但是隱藏V.

所以我寫了這段代碼來做它,但是當我按下X時,它顯示了BOTH V(打開類) ,但我想只顯示其中之一,這是在父母的DIV:

$('.close').click(function(){ // click X makes 
    $(this).parent().css('height','20px'); // parent div's height = 20px 
    $(this).hide('fast'); //hide X 
    $('.open').show('fast');} //unhide V 
); 
$('.open').click(function() { 
    $(this).parent().css('height','220px');} // change height of parent div to 220px 
    $(this).hide('fast'); //hide V 
    $('.close').show('fast');} //unhide X 
); 

如何隱藏,僅顯示的V之一,這是父DIV,兒童是X的父(類.close)。

回答

2

由於XV是兄弟姐妹,你可以用恰當地命名爲siblings()方法:

$(".close").click(function() { 
    $(this).parent().css("height", "20px") 
      .end().hide("fast") 
      .siblings(".open").show("fast"); 
}); 

$(".open").click(function() { 
    $(this).parent().css("height", "220px") 
      .end().hide("fast") 
      .siblings(".close").show("fast"); 
}); 
2

取而代之的是:

// This code unhides ALL Vs because $('.open') selects ALL anchors with the class 
$('.open').show('fast');} //unhide V 

使用本:

// This code unhides only the V you want because it selects only one anchor: 
// the one which is next to the clicked element $(this) in your HTML. 
$(this).siblings('.open').show('fast');} //unhide V 

同樣的變動應以 「取消隱藏X」 線進行。

+0

謝謝你,我不知道兄弟姐妹()方法 – Sindbag