jQuery on(click)doesn't work with two btns [关闭]

hlswsv35  于 2023-06-29  发布在  jQuery
关注(0)|答案(2)|浏览(169)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答复。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
6天前关闭
Improve this question
我有个问题带有class .sert_btn的两个按钮应切换图像的类别。左边的按钮工作在一个正确的方式,但右边的一个不。帮助PLS
类被动-显示:无;
我尝试了 $(document) 的另一种构造,如 $('. sertbtn)$('#btn_r '),但结果是一样的

let i = 0;
$(document).on('click', '.sert_btn', function() {
  i++;
  if (i % 2 == 0) {
    $('#s_1').addClass('passive');
    $('#s_2').removeClass('passive');

  } else {
    $('#s_2').addClass('passive');
    $('#s_1').removeClass('passive');
  }
});
.passive { display: none }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<div class="docs docs_dt">
  <button class="sert_btn">Click</button>
  <img id="s_1" class="sert_img" src="https://pngfre.com/wp-content/uploads/Turtle-1-300x187.png">
  <img id="s_2" class="sert_img" src="https://pngfre.com/wp-content/uploads/Penguin-png-1-155x300.png">
  <button id="btn_r" class="sert_btn">Click</button>
</div>
qyzbxkaa

qyzbxkaa1#

这样更简单,更有意义

$(document).on('click', '.sert_btn', function() {
  // show left image when left is clicked, show right when right is clicked
  //$('#s_1').toggleClass('passive', this.id === "btn_l");
  //$('#s_2').toggleClass('passive', this.id === "btn_r");
  // toggle whenever either button is clicked
  $('#s_1').toggleClass('passive');
  $('#s_2').toggleClass('passive');
});
.passive {
  display: none
}
img { height:50px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<div class="docs docs_dt">
  <button id="btn_l" class="sert_btn">Click</button>
  <img id="s_1" class="sert_img passive" src="https://pngfre.com/wp-content/uploads/red-arrow-27-1-1024x1024.png">
  <img id="s_2" class="sert_img" src="https://pngfre.com/wp-content/uploads/red-arrow-26-1-1024x1024.png">
  <button id="btn_r" class="sert_btn">Click</button>
</div>
utugiqy6

utugiqy62#

这段代码应该在每次单击这两个按钮中的任何一个时切换图像上的类。

$('.sert_btn').click(function() {
  const hasPassive = $('#s_1').hasClass('passive');
  $('#s_1').toggleClass('passive', !hasPassive);
  $('#s_2').toggleClass('passive', hasPassive);
});
.passive { display: none }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="docs docs_dt">
  <button class="sert_btn">Click</button>
  <img id="s_1" class="sert_img passive" src="https://static-cdn.jtvnw.net/ttv-boxart/509658-188x250.jpg">
  <img id="s_2" class="sert_img" src="https://static-cdn.jtvnw.net/ttv-boxart/516575-188x250.jpg">
  <button id="btn_r" class="sert_btn">Click</button>
</div>

相关问题