javascript – 无法使用.not()或:不正确

为什么我无法将.red类添加到.out但排除最接近的?

$('.ring').on('click', function() {

  $(this).not().closest('out').addClass('red');
});
div {
  height: 100px;
  width: 100px;
  float: left;
  margin: 2px;
}

.ring {
  background: grey;
}

.out {
  background: khaki;
}

.red {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>

最佳答案 我会使用这样的索引来做到这一点:

$('.ring').on('click', function() {
  $(".red").removeClass("red");
  var index = $(".ring").index(this);  
  $(".out").not(":eq("+index+")").addClass('red');
});
div {
  height: 100px;
  width: 100px;
  float: left;
  margin: 2px;
}

.ring {
  background: grey;
}

.out {
  background: khaki;
}

.red {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
<div class="map">
  <div class="data">
    <div class="ring"></div>
  </div>
  <div class="out"></div>
</div>
点赞