简体   繁体   中英

Jquery: Hide all children, then show a specific element

I want to hide all child elements in a 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); But nothing displays...

What am i doing wrong?

You need to hide the children and not the containing 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.

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;

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.

You then need to pass a string (which is a valid jQuery selector) to subDisplay() ;

subDisplay('#DivIwantToShow');

To summarize the great comments from @dotweb and @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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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