在 Jquery 中隐藏父 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1028894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hiding parent divs in Jquery
提问by viv
I am having a simple div structure ( see below ). All I am trying to do is when the div id "interviewer-Button" is clicked the following div's should appear and when the div id "elt" is clicked divs from id "parent0" till the end should hide.
我有一个简单的 div 结构(见下文)。我想要做的就是当 div id“interviewer-Button”被点击时,下面的 div 应该出现,当 div id“elt”被点击时,从 id“parent0”到最后的 div 应该隐藏。
The display part works fine. However, when I try to hide, it just does NOT hide. When i click on the div id "elt" the alert message "hh" (see below) gets thrown!! Weird. Any help on how to hide this?
显示部分工作正常。但是,当我尝试隐藏时,它并没有隐藏。当我单击 div id“elt”时,会抛出警报消息“hh”(见下文)!!奇怪的。关于如何隐藏它的任何帮助?
<div id = "interviewer-Button">
Interviewer
<div id = "parent0">
Viv
<div id = "parent1">
Parent
<div id = "elt">
Close
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#parent0").hide();
$("#interviewer-Button").click(function() { alert("hh");$("#parent0").show(); });
$("#elt").click( function () {
$(this).parent().parent().hide();
});
});
</script>
回答by tvanfosson
You need to stop propagation of the click event in the handler for the inner element. Without that the handler for the parent will also be invoked. See the jQuery event objectfor more info.
您需要停止内部元素处理程序中单击事件的传播。如果没有,也将调用父级的处理程序。有关更多信息,请参阅jQuery 事件对象。
$("#elt").click( function (e) {
e.stopPropagation();
$(this).parent().parent().hide();
});
回答by Stephen Smith
n/aUsed a combination of the above. Thanks to both members for their answers. great help.
n/a 使用上述的组合。感谢两位成员的回答。很大的帮助。
jQuery(function ($) {
$('.coffee-strength p span').each(function () {
var string = $.trim($(this).text());
if(string!="22"){
$(this).html('<img src="/images/' + string + '.png" alt="' + string + '" />');
}else{
$(this).parent().parent().hide();
}
});
});
</script>
回答by Cezary Daniel Nowak
You can also take advantage of event propagation and attach just one event:
您还可以利用事件传播并仅附加一个事件:
$(function() {
$("#parent0").hide();
$("#interviewer-Button").on('click', function(e){
$(this).find('#parent0').toggle(e.target.id !== 'elt');
});
});