Javascript Jquery:隐藏所有子元素,然后显示特定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8744404/
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
Jquery: Hide all children, then show a specific element
提问by Christian Bekker
I want to hide all child elements in a div. And then show a specific one passed on to the function.
我想隐藏 div 中的所有子元素。然后显示一个传递给函数的特定的。
function subDisplay(name) {
$("#navSub").each(function() {
$(this).hide();
});
$(name).show();
}
then i call the function from an onmouse event like: subDisplay(#DivIwantToShow);
But nothing displays...
然后我从一个 onmouse 事件调用该函数,例如:subDisplay(#DivIwantToShow);
但没有任何显示...
What am i doing wrong?
我究竟做错了什么?
回答by Brandon Kindred
You need to hide the children and not the containing div.
您需要隐藏孩子而不是包含 div。
$("#navSub").children().hide();
$("#navSub").children().hide();
So now if the div you are trying to show is an element in the parent div it will still show while the others stay hidden.
所以现在,如果您尝试显示的 div 是父 div 中的一个元素,它仍然会显示,而其他人则保持隐藏状态。
回答by Matt
If you're targeting the children of #navSub
, you need target them and hide them, rather than the element navSub
; which you can do using the children()
method;
如果你的目标是 的孩子#navSub
,你需要定位他们并隐藏他们,而不是元素navSub
;您可以使用该children()
方法进行操作;
function subDisplay(name) {
$('#navSub').children().hide();
$(name).show();
};
Otherwise, it appears you have multiple elements with the same ID in your DOM, which is not allowed.
否则,您的 DOM 中似乎有多个具有相同 ID 的元素,这是不允许的。
You then need to pass a string (which is a valid jQuery selector) to subDisplay()
;
然后,您需要将一个字符串(这是一个有效的 jQuery 选择器)传递给subDisplay()
;
subDisplay('#DivIwantToShow');
回答by Stefan
To summarize the great comments from @dotweb and @Matt;
总结@dotweb 和@Matt 的精彩评论;
function subDisplay(name) {
$('#navSub').hide();
$(name).show();
}
subDisplay('#DivIwantToShow');
回答by kaz
function subDisplay(name) {
$("#navSub").hide();
$('#'+name).show();
}
回答by Teun Pronk
if the name of the element is passed in name use this:
如果元素的名称在 name 中传递,请使用:
if($(this).attr('name') != name){
//Hide it
} else {
//show it
}
回答by Chaitanya Bhojne
If you want to hide child divusing class.
如果要使用class隐藏子 div。
<div class="parent_div">
<div class="child_div">1st div</div>
<div class="child_div">2nd div</div>
</div>
$(document).ready(function(){
$(".parent_div").on('click',function(){
$j(this).find("div").toggle();
})
})
回答by peduarte
Try having it outside of the loop, like so:
尝试将其置于循环之外,如下所示:
function subDisplay(name) {
$("#navSub").hide();
$(name).show();
}