【问题标题】:Close Button Not Removing Classes关闭按钮不删除类
【发布时间】:2018-09-20 10:26:49
【问题描述】:

所以,我不确定我做错了什么,因为我在控制台中没有收到任何错误,并且我注释掉了我的其他 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 -->

【问题讨论】:

  • 这些模态有多少种?
  • 现在只有一个。将要转换为 WordPress,所以我只需要确保一个工作正常。
  • 如果这些要重复,您需要删除关闭按钮上的 id,或者使其唯一,因为 id 不应重复。
  • 除此之外,您是说兄弟姐妹方法都不起作用吗?还是'.modal-image-caption' 有效而'.modal-image &gt; img' 无效?因为从技术上讲,第二个选择器没有兄弟姐妹
  • 正确,都不行。我最初只是将它们选为 $('.modal-img > img') 和 $('.modal-image-caption')。另外,关于 id,我只是把它放在 S 和 G 的位置。我最初只是把它当作一个关闭类。

标签: javascript jquery html image


【解决方案1】:

.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>

【讨论】:

  • 是的,做到了。谢谢!
  • @valtro05 请注意,我拿走了关闭按钮的 ID,并将关闭按钮处理程序改为引用关闭类。
猜你喜欢
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多