I'm attempting to create a simple, multi-tabbed navigation that utilizes a single web page. I have my content laid out as so:
HTML
<ul id="nav">
<li><a href="tab1">Tab 1</a></li>
<li><a href="tab2">Tab 2</a></li>
<li class="active"><a href="tab3">Tab 3</a></li>
</ul><!--/#nav-->
<div id="content-box">
<div id="tab1">
<!--content from tab1-->
</div><!--/#tab1-->
<div id="tab2">
<!--content from tab2-->
</div><!--/#tab2-->
<div id="tab3">
<!--content from tab3-->
</div><!--/#tab3-->
</div><!--/#content-box-->
jQuery:
$("#nav li").on("click", function(event){
$("#nav li").removeClass("active");
$(this).addClass("active");
$("#content-box").children().hide();
});
My problem is that I don't know how to link the li
with class active
to the corresponding div
. All of my tab divs are set to hidden, and I have a class called .activeSlide
which turns sets visibility: visible
.
use html 5 data
attributes to link the div
html
<ul id="nav">
<li data-content="tab1">Tab 1</li>
<li data-content="tab2">Tab 2</li>
<li data-content="tab3" class="active">Tab 3</li>
</ul><!--/#nav-->
jquery
$("#nav li").on("click", function(event){
$("#nav li").removeClass("active");
$(this).addClass("active");
$("#content-box").children().hide();
$('#'+ $(this).data('content')).show();
//OR
$("#content-box").children().removeClass('activeSlide');
$('#'+ $(this).data('content')).addClass('activeSlide');
});
updated
add this in ready function
$(document).ready(){
$("#content-box").children().hide();
$("#nav li").on("click", function(event){
...... //above function goes here
});
});
however i recommned you to use jquery ui tab instead of reinventing the wheel... :)
At the end of your click event:
$('#' + $('a', this).attr('href')).show();
I would caution, if you're planning to have a lot of content on a single web page, you may want to consider a way for users to bookmark certain content, which the above design alone would make quite difficult.
Change to this,
HTML
Remove the id tab1, tab2, tab3. Place class "tab instead".
Like,
<div class="tab">
instead of, id="tab1" & "tab2" & "tab3"
JAVASCRIPT
$("#nav li")
.live("click", function(event){
var _index = $(this).index();
$(".tab").hide();
$(".tab:eq("+_index+")").show();
$(this).siblings().removeClass('active');
$(this).addClass('active');
});
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.