切换$(this)元素的兄弟元素的可见性没有唯一的ID [jQuery]

时间:2017-03-29 10:58:46

标签: javascript jquery jquery-selectors toggle selector

我需要div.edit-button切换其兄弟div.additionalFieldForm

请注意,页面上有多个div.edit-buttondiv.additionalFieldForm,但我想定位同一家庭中的div.additionalFieldForm家庭& #34;作为点击的div.edit-button



$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).closest("div").prev().toggle();

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm">Content</div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm">Content</div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
</ul>
&#13;
&#13;
&#13;

我已尝试过其他选择器,但我无法专门定位被点击的编辑按钮的div.additionalFieldForm兄弟。

编辑:我意识到必定存在潜在问题,因为选择器适用于jsFiddle(http://jsfiddle.net/wf7jjoq7/),但不适用于我的网站,没有任何控制台错误。

3 个答案:

答案 0 :(得分:0)

尝试使用siblings()

$(".edit-button").click(function () {  
  $(this).siblings(".additionalFieldForm").toggle();
});

答案 1 :(得分:0)

试试这个解决方案:

&#13;
&#13;
$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).parent().find(".additionalFieldForm").first().toggle();

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

li是共同的父母。所以,

$(".edit-button").click(function () {  
 $(this).closest("li").find(".additionalFieldForm").toggle();
});