简体   繁体   English

Jquery:隐藏所有子项,然后显示特定元素

[英]Jquery: Hide all children, then show a specific element

I want to hide all child elements in a div. 我想隐藏div中的所有子元素。 And then show a specific one passed on to the function. 然后显示传递给函数的特定一个。

function subDisplay(name) {
   $("#navSub").each(function() {
      $(this).hide();
   });
   $(name).show();
}

then i call the function from an onmouse event like: subDisplay(#DivIwantToShow); 然后我从一个onmouse事件中调用该函数,如: subDisplay(#DivIwantToShow); But nothing displays... 但没有任何显示......

What am i doing wrong? 我究竟做错了什么?

You need to hide the children and not the containing div. 你需要隐藏孩子而不是隐藏的div。

$("#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中的一个元素,它仍将显示而其他div保持隐藏状态。

If you're targeting the children of #navSub , you need target them and hide them , rather than the element navSub ; 如果你的目标是#navSub的孩子,你需要定位它们并隐藏它们 ,而不是元素navSub ; which you can do using the children() method; 你可以用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');

To summarize the great comments from @dotweb and @Matt; 总结@dotweb和@Matt的好评;

function subDisplay(name) {
   $('#navSub').hide();
   $(name).show();
}

subDisplay('#DivIwantToShow');

if the name of the element is passed in name use this: 如果在名称中传递元素的名称,请使用以下命令:

    if($(this).attr('name') != name){
    //Hide it
    } else {
   //show it
}
function subDisplay(name) {
   $("#navSub").hide();
   $('#'+name).show();
}

Try having it outside of the loop, like so: 尝试在循环之外使用它,如下所示:

function subDisplay(name) {

     $("#navSub").hide();

     $(name).show();
}

http://jsfiddle.net/peduarte/m2pj8/ http://jsfiddle.net/peduarte/m2pj8/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM