Hi im trying to figure out how to hide and show content using multi开发者_C百科ple links. Ex.
<a href="#">Content 1</a>
<a href="#">Content 2</a>
<a href="#">Content 3</a>
<div class="show">content #1</div>
<div class="hidden">content #2</div>
<div class="hidden">content #3</div>
So when someone clicks Content #2, it shows content #2 and hides content #1
Your links and divs have only the loosest of hooks on which to hang this sort of behavior. Perhaps you really do mean to associate links with their respective divs by ordinal position -- but if not, one way to start is by adding some meaningful id
s. So:
<div id="linkarea">
<a href="#" id="link-1">Content 1</a>
<a href="#" id="link-2">Content 2</a>
</div>
and then
<div id="contentarea">
<div id="c-1">content #1</div>
<div id="c-2">content #2</div>
</div>
To make it work:
$('div#linkarea a').click( function(ev){
ev.preventDefault(); // suppress natural click
var idx = this.id.split('-')[1]; // grab the link "number"
$('div#contentarea div[id=c-'+idx+']') // find respective div
.show() // show it
.siblings() // get its siblings
.hide(); // and hide them
});
});
Here's a working fiddle.
I would approach this in a slightly different way.
Instead of including the links in the HTML, generate them with javascript. This way, if someone has JS disabled, then they won't see the useless links.
<div title="Content 1">content #1</div>
<div title="Content 2">content #2</div>
<div title="Content 3">content #3</div>
Then the JS:
var $divs = $('div'); // or whatever selector is appropriate, maybe classes are needed?
var $linkDiv = $("<div></div>").insertBefore($divs);
$divs.each(function(index) {
var $t = $(this);
$("<a></a>", { href: '#', text: this.title })
.click(function(e) {
e.preventDefault();
$t.toggle('slow');
})
.appendTo($linkDiv)
;
this.removeAttribute('title'); // to avoid ugly hover tooltips
if (index > 0) $t.hide();
});
Try .toggle() along with .hide()
http://api.jquery.com/toggle/
http://api.jquery.com/hide/
There are examples on those pages which cover what you want to do.
精彩评论