Jquery: Hide all children, then show a specific element

后端 未结 7 1704
忘了有多久
忘了有多久 2021-01-03 17:59

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(functi         


        
相关标签:
7条回答
  • 2021-01-03 18:15

    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.

    0 讨论(0)
  • 2021-01-03 18:23
    function subDisplay(name) {
       $("#navSub").hide();
       $('#'+name).show();
    }
    
    0 讨论(0)
  • 2021-01-03 18:27

    If you want to hide child div using class.

    <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();
        })
    })
    
    0 讨论(0)
  • 2021-01-03 18:31

    To summarize the great comments from @dotweb and @Matt;

    function subDisplay(name) {
       $('#navSub').hide();
       $(name).show();
    }
    
    subDisplay('#DivIwantToShow');
    
    0 讨论(0)
  • 2021-01-03 18:33

    Try having it outside of the loop, like so:

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

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

    0 讨论(0)
  • 2021-01-03 18:34

    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');
    
    0 讨论(0)
提交回复
热议问题