从您在文章中提到的 Soh Tanaka 的示例页面中提取代码:
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
关键位是将代码修复为仅引用当前选项卡组,以便在选项卡之间切换。这是通过确保在不需要全局上下文的地方,只有本地组,我们更改选择器来实现的。当从一组选项卡引用它们的内容时,问题是如何将一个与另一个匹配,这可以使用一些常见的 ID 系统来完成,或者如果假设选项卡位于其内容之前,没有重叠,那么我们可以只需tab_container
从选项卡集中找到下一个。
一、初始化:
$(".tab_content").hide();
好的,我们想隐藏所有这些。
$("ul.tabs li:first").addClass("active");
$(".tab_content:first").show();
不好,这会引用页面上的所有标签组,需要具体。
$("ul.tabs").each(function() {
$(this).find('li:first').addClass("active");
$(this).nextAll('.tab_container:first').find('.tab_content:first').show();
});
.click()
活动开始好了,绑定一切都ul.tabs li
很好。在它里面需要改变选择器。
$("ul.tabs li").click(function() {
var cTab = $(this).closest('li');
cTab.siblings('li').removeClass("active");
cTab.addClass("active");
cTab.closest('ul.tabs').nextAll('.tab_container:first').find('.tab_content').hide();
var activeTab = $(this).attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
最后一部分activeTab
已经很好了,只是注意不要重复使用 ID。
见演示:http: //jsfiddle.net/uyvUZ/1/
视觉上更容易,但演示不同:http: //jsfiddle.net/uyvUZ/2/