简体   繁体   中英

How to show/hide DIVs with jQuery

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

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

Link calling the function:

<ul>
  <a style="cursor:pointer;" onclick="showPage('#home_page1')">
    <li>Show Page 1</li>
  </a>
  <a style="cursor:pointer;" onclick="showPage('#home_page2')">
    <li>Show Page 2</li>
  </a>
</ul>

DIV s on page:

<div id="midRight">
    <div id="home_page1">Content 1</div>
    <div id="home_page2" style="display:none;">Content 2</div>
</div>

The function showPage ends up hiding every div within midRight , while on JSFiddle, the click event doesn't seem to be handled at all .

What is the correct way to show/hide a DIV with jQuery?

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();    
}

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/

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();
});

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();
    });
});

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