2011-09-10 31 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