我的切换操作都已设置好并且正常工作。我想添加一些功能,如果你去example.com/#section,该页面将打开该特定部分。我想我需要以某种方式使用location.hash,我只是不确定如何将它应用到我已有的。
的jQuery
$(document).ready(function(){
$('ul.tabs li').click(function(){
var tab_id = $(this).attr('data-tab');
$('ul.tabs li').removeClass('current');
$('.press-tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
})
});
HTML
<ul class="press-toggle tabs">
<li id="news-release" data-tab="tab-1" class="tab-link current">News Releases</li>
<li id="events-presentations" data-tab="tab-2" class="tab-link">Events & Presentations</li>
<li id="media" data-tab="tab-3" class="tab-link">Media Coverage</li>
<li id="publications" data-tab="tab-4" class="tab-link">Publications</li>
</ul>
<div class="press-tab-content current" id="tab-1">
NEWS RELEASES CONTENT HERE
</div>
<div class="press-tab-content" id="tab-2">
EVENTS & PRESENTATIONS CONTENT HERE
</div>
<div class="press-tab-content" id="tab-3">
MEDIA COVERAGE CONTENT HERE
</div>
<div class="press-tab-content" id="tab-4">
PUBLICATION CONTENT HERE
</div>
答案 0 :(得分:1)
var section = window.location.hash.substr(1); // get section after hash from url .. your url should be something like website.com#tab-1
$('ul.tabs li').filter(function(){ // use .filter to find the li which data-tab equal to this section
return $(this).attr('data-tab') == section;
}).click(); // trigger click it
注意:在您的代码中,我更喜欢使用
.on('click' , function(){
.click(function(){
并且:您可以使您的代码看起来像这样
$(document).ready(function(){
var section = window.location.hash.substr(1);
$('ul.tabs li').click(function(){ // click
var tab_id = $(this).attr('data-tab');
$('ul.tabs li').removeClass('current');
$('.press-tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
}).filter(function(){ // filter
return $(this).attr('data-tab') == section;
}).click(); //trigger click
});
注2:如果
.attr('data-tab')
无效,您可以使用.data('tab')
代替