How to show/hide DIVs with jQuery

前端 未结 4 1107
难免孤独
难免孤独 2021-01-17 04:28

I want to make a function to show and hide a div tag and hide all others:

function showPage(showdiv){
    $(\'#midRight\').not(showdiv).hide(); 
    $(showdi         


        
相关标签:
4条回答
  • 2021-01-17 04:34

    The fiddle isn't working because it can't find the function, it can't find the function because you specified the functions to be interpreted during onLoad. To fix it, in the upper left of the jsFiddle, set the dropdown from onLoad to No wrap - in <body>.

    Here's a working version that doesn't use in-line events:

    http://jsfiddle.net/gRDdC/

    <ul>
     <li>
      <a style="cursor:pointer;" class="nav-link" href="#home_page1">Show Page 1</a>
     </li>
     <li>
      <a style="cursor:pointer;" class="nav-link" href="#home_page2">Show Page 2</a>
     </li>
    </ul>
    
    <div id="midRight">
        <div id="home_page1">Content 1</div>
        <div id="home_page2" style="display:none;">Content 2</div>
    </div>
    
    
    $(document).ready(function() {
        $('.nav-link').click(function(e) {
            e.preventDefault();
            $('#midRight > div').hide();
            $($(this).attr('href')).show();
        });
    });
    
    0 讨论(0)
  • 2021-01-17 04:43

    Fixed up some syntax errors. As the comments say, you're appending an empty string with the variable, just use the variable. Also, you need to tell the selector to select the children of the targetted container:

    function showPage(showdiv){
        $('#midRight').children().not(showdiv).hide();  
        $(showdiv).show();  
    }
    

    Demo: http://jsfiddle.net/ACGMj/1/

    0 讨论(0)
  • 2021-01-17 04:50

    DEMO

    function showPage(showdiv){
        $(showdiv).show().siblings().hide();
    }
    

    Or, without using IDs:

    DEMO

    $('ul a').click(function() {
        var index = $(this).index();
        $('#midRight > div').hide().eq(index).show();
    });
    
    0 讨论(0)
  • 2021-01-17 04:58

    You could write you selector to hide all child div's of midRight, then show the div with the passed ID. No need to cast to a String, since that is what you are passing:

    function showPage(showdiv){
        $('#midRight > div').hide()  
        $(showdiv).show();    
    }
    
    0 讨论(0)
提交回复
热议问题