首页 > 解决方案 > 关闭按钮不删除类

问题描述

所以,我不确定我做错了什么,因为我在控制台中没有收到任何错误,并且我注释掉了我的其他 JQuery/JavaScript 代码并且问题仍然存在。当我单击缩略图时,类添加得很好,但是当我单击关闭按钮时,类不会删除。如果我在单击关闭按钮时添加警报功能,它可以正常工作。

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

  $(this).find('.modal').addClass('active');
  $(this).find('.modal-image > img').addClass('active');
  $(this).find('.modal-image-caption').addClass('active');

});

$('#close').on('click', function() {

  $(this).parent('.modal').removeClass('active');

  $(this).siblings('.modal-image > img').removeClass('active');
  $(this).siblings('.modal-image-caption').removeClass('active');

});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>


<div class="modal">

  <span class="close" id='close'>&times;</span>

  <div class="modal-image">

    <img src="https://via.placeholder.com/150x150" alt="">

  </div>
  <!-- modal-image -->

  <div class="modal-image-caption text-center">

    <p>This is some example text</p>

  </div>
  <!-- modal-image-caption -->

</div>
<!-- modal -->

标签: javascriptjqueryhtmlimage

解决方案


.thumbnail在包含模态的假设下,单击close按钮会冒泡并再次触发活动。

我添加return false;到您的功能的末尾。

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

  $(this).find('.modal').addClass('active');
  $(this).find('.modal-image > img').addClass('active');
  $(this).find('.modal-image-caption').addClass('active');

});

$('.close').on('click', function() {
  $(this).parent('.modal').removeClass('active');

  $(this).siblings('.modal-image > img').removeClass('active');
  $(this).siblings('.modal-image-caption').removeClass('active');

  return false;
});
.active {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML:
<div class="thumbnail">
  <div class="modal">

    <span class="close">&times;</span>

    <div class="modal-image">

      <img src="./img/dish.jpg" alt="">

    </div>
    <!-- modal-image -->

    <div class="modal-image-caption text-center">

      <p>This is some example text</p>

    </div>
    <!-- modal-image-caption -->

  </div>
  <!-- modal -->
</div>


推荐阅读