jquery - 打开后如何使用 jQuery 关闭/隐藏此 div?
问题描述
以下链接将说明我的意思。您单击第一个红色框以显示蓝色框。然后,理论上,您应该可以再次单击绿色小按钮关闭蓝色框。它并不完全按照我想要的方式工作。
$('.card').click(function(){
if($(".expand").is(":visible")){
} else {
$(this).children(".expand").show();
}
});
$('.close').click(function(){
$(this).parent(".expand").hide();
});
.card {
height: 256px;
width: 256px;
background-color: red;
}
.expand {
display: none;
position: relative;
height: 256px;
width: 256px;
left: 256px;
background-color: blue;
}
.close {
margin: 16px;
position: absolute;
height: 16px;
width: 16px;
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="expand">
<div class="close">
</div>
</div>
</div>
解决方案
由于事件传播,您的子 div 也会触发父函数。
您需要使用停止传播:e.stopPropagation()
$('.card').click(function(){
if(!$(".expand").is(":visible")){
$(this).children(".expand").toggle();
}
});
$('.close').click(function(e){
e.stopPropagation()
$(this).parents('.expand').toggle();
});
.card {
height: 256px;
width: 256px;
background-color: red;
}
.expand {
display: none;
position: relative;
height: 256px;
width: 256px;
left: 256px;
background-color: blue;
}
.close {
margin: 16px;
position: absolute;
height: 16px;
width: 16px;
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="expand">
<div class="close">
</div>
</div>
</div>
推荐阅读
- angular - Angular 6数据表如何从字符串中留下空格
- android - 如何为 Android 编译 OpenSSL 1.1.1
- python - 失败的质数检查器
- sql - INSERT INTO ... SELECT 具有更多 SELECT 列
- c++ - 使用不兼容的分配器复制分配无序映射
- r - cluster walktrap 返回三个社区,但在绘制时它们都在彼此之上,没有可见的聚类
- qt - 如何在 Qt QML 中从“onEditingFinished”更改文本字段属性
- jquery - 替换其他选择框的选择选项列表值
- owl - 使用 Protege 中两个数据属性之间的关系定义类限制
- java - 集成测试的边界