Bootstrap load tab from external URL

岁酱吖の 提交于 2021-01-28 14:16:08

问题


I have looked at various pages on how to load a specific bootstrap tab from an external URL e.g. http://pagename.html#tab1 and I have tried to implement, but I just cannot get it to work. Including the base of the code I am using here - the tabs work fine, but I cannot get them to load from an external URL

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>PAGE TITLE</title>
<meta name="description" content="">
<meta name="author" content="">
<link href="../css/bootstrap.min.css" rel="stylesheet">
     <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="../js/bootstrap.min.js"></script>
<script>
$('#myTab a').click(function (e) {
e.preventDefault();
var pattern=/#.+/gi //use regex to get anchor(==selector)
var contentID = e.target.toString().match(pattern)[0]; //get anchor   
$('.nav-tabs a[href="'+contentID+'"]').tab('show') ;         
});
</script>     
</head>
<body>
<div class="container">
<a href="#pane1">PANE1</a>
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="active"><a href="#pane1" data-toggle="tab">Tab 1</a></li>
<li><a href="#pane2" data-toggle="tab">Tab 2</a></li>
<li><a href="#pane3" data-toggle="tab">Tab 3</a></li>
<li><a href="#pane4" data-toggle="tab">Tab 4</a></li>
</ul>
<div class="tab-content">
<div id="pane1" class="tab-pane active">
<h4>The Markup</h4>
<pre>Code here ...</pre>
</div>
<div id="pane2" class="tab-pane">
<h4>Pane 2 Content</h4>
<p> and so on ...</p>
</div>
<div id="pane3" class="tab-pane">
<h4>Pane 3 Content</h4>
</div>
<div id="pane4" class="tab-pane">
 <h4>Pane 4 Content</h4>
</div>
</div><!-- /.tab-content -->
</div><!-- /.tabbable -->
</div>
</body>
</html>

回答1:


Just found the answer - it's really easy and it works! Just use this script inside the head:

$(function () {
var activeTab = $('[href=' + location.hash + ']');
activeTab && activeTab.tab('show');
});

Apparently it just checks for the hash in the URL and sets it to the active tab. Tested and it works!



来源:https://stackoverflow.com/questions/25333113/bootstrap-load-tab-from-external-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!