我正在开发一个网页,其中我使用Twitter的引导框架和他们的引导标签JS。它的工作很好,除了一些小问题,其中之一是我不知道如何直接从外部链接到一个特定的选项卡。例如:
<a href="facility.php#home">Home</a>
<a href="facility.php#notes">Notes</a>
当从外部页面点击链接时,应该分别转到Home选项卡和Notes选项卡
我正在开发一个网页,其中我使用Twitter的引导框架和他们的引导标签JS。它的工作很好,除了一些小问题,其中之一是我不知道如何直接从外部链接到一个特定的选项卡。例如:
<a href="facility.php#home">Home</a>
<a href="facility.php#notes">Notes</a>
当从外部页面点击链接时,应该分别转到Home选项卡和Notes选项卡
当前回答
$(function(){
var hash = window.location.hash;
hash && $('ul.nav a[href="' + hash + '"]').tab('show');
});
这段来自http://github.com/twitter/bootstrap/issues/2415#issuecomment-4450768的代码非常适合我。
其他回答
对于引导3:
$('.nav-tabs a[href="#' + tabID + '"]').tab('show');
https://jsfiddle.net/DTcHh/6638/
基于Peter的回答,并结合https://stackoverflow.com/a/901144/1604205,下面是JS中的代码:
<script>
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
$activetabhome = (params.activeTab === null || params.activeTab == 'home') ? 'class="active"' : '';
$activetabprofile = (params.activeTab == 'profile') ? 'class="active"' : '';
</script>
<li $activetabhome><a href="#home">Home</a></li>
<li $activetabprofile><a href="#profile">Profile</a></li>
@flynfish + @Ztyx解决方案,我用于嵌套选项卡:
handleTabLinks();
function handleTabLinks() {
if(window.location.hash == '') {
window.location.hash = window.location.hash + '#_';
}
var hash = window.location.hash.split('#')[1];
var prefix = '_';
var hpieces = hash.split('/');
for (var i=0;i<hpieces.length;i++) {
var domelid = hpieces[i].replace(prefix,'');
var domitem = $('a[href=#' + domelid + '][data-toggle=tab]');
if (domitem.length > 0) {
domitem.tab('show');
}
}
$('a[data-toggle=tab]').on('shown', function (e) {
if ($(this).hasClass('nested')) {
var nested = window.location.hash.split('/');
window.location.hash = nested[0] + '/' + e.target.hash.split('#')[1];
} else {
window.location.hash = e.target.hash.replace('#', '#' + prefix);
}
});
}
儿童应该有class="nested"
这段代码根据#散列选择正确的选项卡,并在单击选项卡时添加正确的#散列。(使用jquery)
在Coffeescript中:
$(document).ready ->
if location.hash != ''
$('a[href="'+location.hash+'"]').tab('show')
$('a[data-toggle="tab"]').on 'shown', (e) ->
location.hash = $(e.target).attr('href').substr(1)
或在JS中:
$(document).ready(function() {
if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');
return $('a[data-toggle="tab"]').on('shown', function(e) {
return location.hash = $(e.target).attr('href').substr(1);
});
});
如果这对任何人来说都很重要,下面的代码很小,工作完美无缺,从URL中获得一个哈希值并显示:
<script>
window.onload = function () {
let url = document.location.toString();
let splitHash = url.split("#");
if (splitHash[1]) {document.getElementById(splitHash[1]).click();}
};
</script>
它所做的是检索id并触发单击事件。简单。