隐藏每个类元素

时间:2018-03-06 10:49:15

标签: jquery

我想为每个" .ImHere"找到父母最近的按钮。类元素。

$('.ImHere').each(function() {
    $(".ImHere" ).parent().nextAll('.add').first().css( "background-color", "red" );
});

https://jsfiddle.net/nf50k7og/42/

但它不起作用

4 个答案:

答案 0 :(得分:3)

this

的回调中再次使用.Imhere代替.each



$('.ImHere').each(function() {
    $(this).parent().nextAll('.add').first().css("background-color", "red");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="unique1">
  <div class="ImHere"></div>
</div>
<button class="zoom" type="button">Zoom</button>
<button class="add" type="button">Add</button>

<div id="unique2">
  <div class=""></div>
</div>
<button class="zoom" type="button">Zoom</button>
<button class="add" type="button">Add</button>

<div id="unique3">
  <div class="ImHere"></div>
</div>
<button class="zoom" type="button">Zoom</button>
<button class="add" type="button">Add</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这个:

    $("document").ready(function() {
      $('.ImHere').each(function() {
        $(".ImHere" ).parent().next("[type='button']").css( "background-color", "red" );
// OR if you want specific class
// $(".ImHere" ).parent().next(".add").css( "background-color", "red" );
      });
    });

https://jsfiddle.net/nf50k7og/54/

答案 2 :(得分:1)

您也可以尝试这样

 $("document").ready(function() { $('.ImHere').parent().next('button').next('button.add').css('background-color','red') });

答案 3 :(得分:0)

我建议你将单位包装在一个容器元素中。您可以使用.closest()遍历共同祖先,然后使用.find()来定位它。

并使用当前元素上下文,即this

$("document").ready(function() {
  $('.ImHere').click(function() {
    $(this).closest('.container').find('.add').css("background-color", "red");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div id="unique1">
    <div class="ImHere">ImHere</div>
  </div>
  <button class="zoom" type="button">Zoom</button>
  <button class="add" type="button">Add</button>

</div>

<div class="container">
  <div id="unique1">
    <div class="ImHere">ImHere</div>
  </div>
  <button class="zoom" type="button">Zoom</button>
  <button class="add" type="button">Add</button>
</div>