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();
}
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:
<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();
});
});
来源:https://stackoverflow.com/questions/17410210/how-to-show-hide-divs-with-jquery