拿这个jsfiddle.如果单击蓝色方块,将出现一个带有紫色子方块的红色方块(如果您是色盲则道歉):
$('#holder').click(function(){
$(this).children('.parent').show();
});
Run Code Online (Sandbox Code Playgroud)
这很好用.单击紫色子方块时,红色父方块应隐藏:
$('.child').click(function(){
$(this).parent().hide();
console.log($(this).parent().css('display'));
});
Run Code Online (Sandbox Code Playgroud)
尽管控制台返回display:none
父元素的css值,但这不起作用.我想知道是否有人可以解释为什么父母不会被隐藏,以及可能有哪些替代隐藏它?
HTML
<div id="holder">
<div class="parent">
<div class="child">
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
#holder {
height: 50px;
width:50px;
background-color: blue
}
.parent {
position:fixed;
top:100px;
left:200px;
display:none;
width:200px;
height:200px;
background-color:red
}
.child {
position:absolute;
width:50px;
height:50px;
background-color:purple
}
Run Code Online (Sandbox Code Playgroud)
JS
$(function(){
$('#holder').click(function(){
$(this).children('.parent').show();
});
$('.child').click(function(){
$(this).parent().hide();
console.log($(this).parent().css('display'));
});
});
Run Code Online (Sandbox Code Playgroud)
您遇到的问题是,在隐藏元素之后,事件会传播到元素#holder
的父.parent
元素,因此您定义的事件处理程序会#holder
再次显示元素.
return false
在事件处理程序的末尾添加以防止传播:
$('.child').click(function(){
$(this).closest('.parent').hide();
console.log($(this).parent().css('display'));
return false;
});
Run Code Online (Sandbox Code Playgroud)