jQuery 子元素>父元素>子元素

3

I have this html-code:

<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(class close)来改变父级 div 的高度为 20px 并显示 V(class open),但是在每个带有 class im 的 div 中单独隐藏 X(class close)。然后按下 V(class open)来将父级 div 的高度更改为 220px 并显示 X,但是隐藏 V。所以我编写了以下代码来实现此目的,但当我按下 X 时,它会同时显示 BOTH V(class open),但我只想显示其中一个,即父级 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
);

如何隐藏和显示父div的子元素V,而该父div是X(class .close)的父元素。
2个回答

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”这一行。

谢谢,我不知道siblings()方法。 - Sindbag

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");
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接