I know the show/hide thing has been covered to death on stack, but I just can't find a solution that works for me, sorry. I've tried several JS/jQuery solutions that I found and can't quite get one to behave the way I'd like.
I have many divs that are very similar in content (content changes slightly based on version selected), and all have the exact same style.
Desired behavior
I'd like one div to show by default with all others hidden. Then, based on a link click, a different version div is displayed and all other content divs are hidden.
Basic HTML
<div class="container">
<h1>Header</h1>
<p>Basic info about page</p>
<ul>
<li><a href="#ver1" id="linkToVer1">Version 1</a></li>
<li><a href="#ver2" id="linkToVer2">Version 2</a></li>
// More links to other divs
</ul>
<div class="content" id="ver1"> // I'd like this div to be the default
Content here // when the page loads. All other divs
</div> // are hidden until a link is clicked.
<div class="content" id="ver2">
Content here
</div>
// More content divs
</div>
I'll have up to a dozen different versions of these content divs.
JS or jQuery is fine, but jQuery is preferred because I'll probably add some kind of show/hide effect. I don't care that greatly about the naming structure of the divs or links.
$("div.containter ul li").each(function(){
$(this).onclick(function(){
$("div.content").hide();
$("div" + $(this).attr("href")).show();
});
});
Wrap that in a $(document).ready
or whereever and you should be good to go my friend. Learn the code, so that in the future, you are gosu.
How about adding some more RESTful behaviour.
$(function(){
// get the location hash
var hash = window.location.hash;
// hide all
$('div.content').hide();
if(hash){
// show the div if hash exist
$(hash).show();
}else{
// show default
$("#ver1").show();
}
$("div.containter ul li a").click(function(){
// hide all
$('div.content').hide();
$($(this).attr("href")).show();
});
});
I suggest you to use on()
jquery function with selector. And also you can show the default div
using css. Here is the complete code.
来源:https://stackoverflow.com/questions/13885256/hide-several-divs-show-1-by-default-and-switch-show-hide-between-them-based