Jquery显示/隐藏/切换元素"靠近"

时间:2015-09-03 03:11:33

标签: javascript jquery

我试图设置它以便"点击我1"只显示"展开我1","点击我2"只显示"扩展我2"等我现在拥有的每个人都会切换一切。我想我需要使用$(this),但我无处可以认为它有效。

标记

<div class="submission">
    <ul>
        <li class="click">Click me 1</li>
        <li>foo</li>
        <li>bar</li>
        <li class="expand">Expand me 1</li>
    </ul>
</div>

<div class="submission">
    <ul>
        <li class="click">Click me 2</li>
        <li>foo</li>
        <li>bar</li>
        <li class="expand">Expand me 2</li>
    </ul>
</div>

<div class="submission">
    <ul>
        <li class="click">Click me 3</li>
        <li>foo</li>
        <li>bar</li>
        <li class="expand">Expand me 3</li>
    </ul>
</div>

Jquery的

$(document).ready(function() {
        $(".submission").find(".click").click(function() {
            $(".expand").slideToggle();
    });
});

CSS

.expand {display: none;}

http://jsfiddle.net/4k9uukL8/

4 个答案:

答案 0 :(得分:0)

您希望将以下某个兄弟元素作为目标

$(document).ready(function() {
  $(".submission .click").click(function() {
    $(this).nextAll(".expand").slideToggle();
    //or $(this).siblings(".expand").slideToggle();    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="submission">
  <ul>
    <li class="click">Click me 1</li>
    <li>foo</li>
    <li>bar</li>
    <li class="expand">Expand me 1</li>
  </ul>
</div>

<div class="submission">
  <ul>
    <li class="click">Click me 2</li>
    <li>foo</li>
    <li>bar</li>
    <li class="expand">Expand me 2</li>
  </ul>
</div>

<div class="submission">
  <ul>
    <li class="click">Click me 3</li>
    <li>foo</li>
    <li>bar</li>
    <li class="expand">Expand me 3</li>
  </ul>
</div>

答案 1 :(得分:0)

您可以使用.parent()选择器

FIDDLE

$(document).ready(function() {
    $(".submission .click").click(function() {
        $(this).parent().find(".expand").slideToggle();
    });
});

documentation

中的更多信息

答案 2 :(得分:0)

尝试使用$("~ .expand", this)处理程序中的Next Siblings Selector ("prev ~ siblings")选择器click来调用.slideToggle()

&#13;
&#13;
$(".submission .click").click(function() {
  $("~ .expand", this).slideToggle()
})
&#13;
.expand {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="submission">
  <ul>
    <li class="click">Click me 1</li>
    <li>foo</li>
    <li>bar</li>
    <li class="expand">Expand me 1</li>
  </ul>
</div>

<div class="submission">
  <ul>
    <li class="click">Click me 2</li>
    <li>foo</li>
    <li>bar</li>
    <li class="expand">Expand me 2</li>
  </ul>
</div>

<div class="submission">
  <ul>
    <li class="click">Click me 3</li>
    <li>foo</li>
    <li>bar</li>
    <li class="expand">Expand me 3</li>
  </ul>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

Pekka的回答可能是最简单的(因此最好)。

替代方案可以是使用&#34;最接近&#34;什么时候不解决直接的父母。

$(this).closest(".submission").find(".expand").slideToggle();