我在page1.htm
上有以下引导药丸:
<div>
<ul class="nav nav-pills nav-stacked" >
<li role="presentation" class=""><a href="someurl.htm#apply" class="js-apply">Apply</a></li>
<li role="presentation" class=""><a href="someurl.html#report" class="js-report">Report</a></li>
<li role="presentation" class=""><a href="someurl.html#book" class="js-book">Book</a></li>
</ul>
</div>
在page2.htm
上我有以下链接
<a class="btn btn-default" href="page1.htm#apply" role="button">Apply</a>
当我点击上面的链接转到page1.htm
时,如何从网址中提取锚点ID属性,将page1.htm
上的列表项设置为具有相同的锚ID属性,即以下list标签应该变为活动状态:
<li role="presentation" class="active"><a href="someurl.htm#apply" >Apply</a></li>
同样,如果我点击以下链接,我想将page1.htm
上的列表项设置为具有相同的锚ID属性。
<a class="btn btn-default" href="page1.htm#report" role="button">Apply</a>
我使用以下内容来获取哈希:
var url = document.location.toString(), idx = url.indexOf("#")
var hash = idx != -1 ? url.substring(idx+1) : "";
答案 0 :(得分:3)
您可以使用window.location.hash
从网址获取ID。从那里循环遍历无序列表的锚点,检查散列的href
值。
此示例使用jQuery。
var hash = window.location.hash
$( '.nav-pills a' ).each( function( i, e ) {
var $a = $( this );
if ( hash && -1 !== $a.attr( 'href' ).indexOf( hash ) ) {
$a.parent().addClass( 'active' ); // add class to <li>
}
} );
这是一个演示代码的jsFiddle:http://jsfiddle.net/6dyee7b0/15/
<ul class="nav-pills">
<li><a href="some-url.html#one">One</a></li>
<li><a href="some-url.html#two">Two</a></li>
<li><a href="some-url.html#three">Three</a></li>
<li><a href="some-url.html#four">Four</a></li>
<li><a href="some-url.html#five">Five</a></li>
<li><a href="some-url.html#six">Six</a></li>
</ul>
.active a {
color: red;
}
答案 1 :(得分:2)
使用js检查哈希的url,然后使用它将类应用于li
if (window.location.hash == "#apply") {
$("ul.nav-pills li:first-child").addClass("active");
}
if (window.location.hash == "#report") {
$("ul.nav-pills li:last-child").addClass("active");
}
答案 2 :(得分:0)
由于您的哈希值很方便地匹配您的类,您可以直接在另一个中使用它:
var wh = window.location.hash.substr(1); // .substr(1) removes the '#'
if (wh === 'apply' || wh === 'report' || wh === 'book') {
$('ul.nav-pills li.'+wh).addClass('active');
}
您可以安全地跳过验证步骤,因为最坏的情况是您将.active
添加到不存在的元素,但显式通常更好...