我是编程新手,我真的想了解我的代码中发生了什么,但与任何事情一样,需要时间。我知道这可能是一个明显显而易见的有人体验,但我无法弄清楚如何做到这一点......我一直在使用Duckett的javascript书作为参考和指南。这段代码是从他那里借来的。
我需要能够引用和显示每个面板。我已经尝试引用index.html#tab-1等。我不知道如何另外设置一个位置以便可以指向它。冗余的方法是为每个面板创建新页面,但我希望内容是动态的,文件结构是干净的。请帮忙。
Html结构:
<ul class="tab-list">
<li class="active"><a class="tab-control" href="#tab-1">Mission & Vision</a></li>
<li><a class="tab-control" href="#tab-2">Facilities & Services</a></li>
<li><a class="tab-control" href="#tab-3">Policies</a></li>
<li><a class="tab-control" href="#tab-4">History</a></li>
</ul>
<div class="tab-panel active" id ="tab-1">
<p> Content etc. </p>
<div class="tab-panel active" id ="tab-2">
<p> Content etc. </p>
<div class="tab-panel active" id ="tab-3">
<p> Content etc. </p>
使用Javascript:
$('.tab-list').each(function(){ // Find lists of tabs
var $this = $(this), // Store this list
$tab = $this.find('li.active'), // Get the active list item
$link = $tab.find('a'), // Get link from active tab
$panel = $($link.attr('href')); // Get active panel
$this.on('click', '.tab-control', function(e) { // When click on a tab
e.preventDefault(); // Prevent link behavior
var $link = $(this), // Store the current link
id = this.hash; // Get href of clicked tab
if (id && !$link.is('.active')) { // If not currently active
$panel.removeClass('active'); // Make panel inactive
$tab.removeClass('active'); // Make tab inactive
$panel = $(id).addClass('active'); // Make new panel active
$tab = $link.parent().addClass('active'); // Make new tab active
}
});
});
答案 0 :(得分:0)
更新了codepen(http://codepen.io/anon/pen/JodKEd#load-tab-2)以使用内部和外部链接。 (并修复了.tab-control
点击功能)
$('.tab-list li').on('click', '.tab-control', function(e){
e.preventDefault();
id = this.hash;
activateTab(id);
});
$("a.direct").on('click',function(e){
e.preventDefault();
id = this.hash;
activateTab(id);
});
function activateTab(id){
var li = $("li a[href="+id+"]").parent();
if (id && !li.is('.active')) {
$("li.active").removeClass('active');
$('.tab-panel').removeClass('active');
$(id).addClass('active');
$("li a[href="+id+"]").parent().addClass("active");
}
}
if(document.location.hash){
//if( write_here_some_check_for_valid_hash: #load-tab-x ){
var hash = document.location.hash.split("-");
var id = "#"+hash[1]+"-"+hash[2];
activateTab(id);
//}
}
在外部链接中使用#load-tab-2
哈希加载tab-2
。哈希中的load
前缀是为了防止页面自动滚动。