我试图在#klapp内单击时切换.klapp的类(从.klappe#label-it)。甚至#klapp本身也被单击。我不能使用唯一的ID。



$('#label-it').click(function() {
  $(this).next(".filter-panel").toggleClass('klapp');
  $(this).next(".filter-panel").toggleClass('klappe');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="label-it" class="label-it">
  <label class="filter-panel">
      <div id="klapp" class="klapp"></div>
   </label>
</div>
<div id="label-it" class="label-it">
  <label class="filter-panel">
      <div id="klapp" class="klapp"></div>
   </label>
</div>
<div id="label-it" class="label-it">
  <label class="filter-panel">
      <div id="klapp" class="klapp"></div>
   </label>
</div>
<div id="label-it" class="label-it">
  <label class="filter-panel">
      <div id="klapp" class="klapp"></div>
   </label>
</div>





我的第一种方法是这样,但是它只更改了#label-it的第一格

$('#label-it').click(function(){
  $("#klapp").toggleClass('klapp');
  $("#klapp").toggleClass('klappe');
});

最佳答案

这里有两个问题。首先,您在多个元素上重复了id属性,这是无效的。您需要将它们全部删除,而仅使用每一个上的class

其次,next()搜索同级元素,而.filter-panel.label-it的子级。因此,您可以使用find()。您还需要在div中选择.filter-panel,因为这就是保存.klapp类的内容。尝试这个:



$('.label-it').click(function() {
  $(this).find(".filter-panel div").toggleClass('klapp klappe');
});

.klapp {
  color: #CCC;
}

.klappe {
  color: #C00;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="label-it">
  <label class="filter-panel">
    <div class="klapp">A</div>
  </label>
</div>
<div class="label-it">
  <label class="filter-panel">
    <div class="klapp">B</div>
  </label>
</div>
<div class="label-it">
  <label class="filter-panel">
    <div class="klapp">C</div>
  </label>
</div>
<div class="label-it">
  <label class="filter-panel">
    <div class="klapp">D</div>
  </label>
</div>

09-12 01:58