开发者

jQuery child>parent>child

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>

and I want to press X (class close) to change height of parent div to 20px and show V (class open), but hide X (class close) in each div with 开发者_运维知识库class im separately. Then press V (class open) to change height of parent div to 220px and show X, but hide V.

So I wrote this code to do it, but when I press X, it show BOTH V (class open), but I want to show only one of them, which is in the parent's 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
);

How can I hide and show only one of V, which is child of the parent div, which is parent of X (class .close).


Since X and V are siblings, you can use the aptly-named siblings() method:

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


Instead of this:

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

use this:

// 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 

The same change should be made to the "unhide X" line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜