来自外部URL的Bootstrap加载选项卡

时间:2014-08-15 19:42:59

标签: jquery twitter-bootstrap tabs external

我查看了有关如何从外部URL加载特定引导程序选项卡的各种页面,例如http://pagename.html#tab1我试图实施,但我无法让它发挥作用。包括我在这里使用的代码的基础 - 选项卡工作正常,但我无法从外部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 个答案:

答案 0 :(得分:3)

刚刚找到答案 - 它真的很容易,而且有效!只需在头部使用此脚本:

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

显然它只是检查URL中的哈希并将其设置为活动选项卡。经过测试,确实有效!