如何将CSS类应用于父元素?

时间:2015-09-21 16:13:42

标签: jquery css twitter-bootstrap

我在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) : "";

3 个答案:

答案 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/

示例代码

HTML

<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>

CSS

.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添加到不存在的元素,但显式通常更好...