javascript - 关闭按钮不删除类
问题描述
所以,我不确定我做错了什么,因为我在控制台中没有收到任何错误,并且我注释掉了我的其他 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'>×</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 -->
解决方案
.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">×</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>
推荐阅读
- asp.net - 无法将表“AspNetRoles”用于实体类型“AspNetRoles”,因为它正在用于实体类型“IdentityRole”
- javascript - 函数调用中的 Javascript
- node.js - 如何使用服务器和客户端文件夹结构将 React/Node 应用程序部署到 Heroku?
- spring-boot - 无效的表单输入会抛出 Bad Request 而不进入 springboot 控制器的方法。怎么处理?
- python - 更改用户密码时在 Django 模型中发送邮件的最佳方式?
- python - ValueError:源代码字符串不能包含空字节 - scipy.io 导入后出错
- typescript - 打字稿:如何推断字符串文字参数类型并将其用于另一个参数类型
- java - 如何使用双重函数作为另一个函数的参数?
- r - 如果值等于 NA,则根据 R 中的份额进行估计
- javascript - JavaScript JSON.parse 字符串错误 - 将值转换为 Infinity