显示/隐藏兄弟divs jquery

时间:2016-12-14 09:25:19

标签: jquery show-hide siblings

我的网页上有多个具有相同类名的div。当我点击span(+/-)时,每个具有相同类名的div都会显示/隐藏。我想在点击+/-按钮时只显示/隐藏兄弟div。我尝试了很多寻找解决方案,但无法达到我的解决方案。感谢...

HTML:

<div class="abc">
  <div class="abc1">
    Stallone Manor is a 200 ft x 130 ft covered AC hall enchanted with a classic touch of Roman grandeur & grace. We offer one of the largest banquet halls in the city.<span>(-)</span>
  </div>
  <div class="abc2">
    Stallone Manor is a 200 ft x 130 ft covered AC hall enchanted with a classic touch<span>(+)</span>
  </div>
</div>

<div class="abc">
  <div class="abc1">
    Stallone Manor is a 200 ft x 130 ft covered AC hall enchanted with a classic touch of Roman grandeur & grace. We offer one of the largest banquet halls in the city.<span>(-)</span>
  </div>
  <div class="abc2">
    Stallone Manor is a 200 ft x 130 ft covered AC hall enchanted with a classic touch<span>(+)</span>
  </div>
</div>

Jquery的:

$(document).ready(function() {
    $(".abc2 span").click(function(){
        $(".abc2").hide();
        $(".abc1").show();
    });
    $(".abc1 span").click(function(){
        $(".abc1").hide();
        $(".abc2").show();
    });
});

小提琴:

http://jsfiddle.net/berqK/42/

1 个答案:

答案 0 :(得分:1)

您必须使用this

来定位元素
$(document).ready(function() {
    $(".abc2 span").click(function(){
        var par = $(this).parent(".abc2").hide();
        par.prev(".abc1").show();
    });
    $(".abc1 span").click(function(){
        var par = $(this).parent(".abc1").hide();
        par.next(".abc2").show();
    });
});

DEMO

您可以像下面那样优化解决方案,

$(document).ready(function() {
    $(".abc1,.abc2").find("span").click(function(){
        var par = $(this).parent().hide(), isAbc1 = par.is(".abc1");
        par[isAbc1 ? "next" : "prev"](isAbc1 ? ".abc2" : ".abc1").show();
    });
});

DEMO