从页面上的其他对应元素添加类到元素

时间:2014-04-18 15:30:49

标签: javascript jquery html html-lists

我希望这个标题不会让人感到困惑。

首先让我说我不是jQuery大师,虽然我可以做一些基本的事情,但这个有点过头了。

描述

我有一个链接列表(4个链接),当用户点击/点击链接时,浏览器跳转到页面下方的相应部分。有一个' Top'链接跳回到列表。简单。

问题

我需要的是一种将类添加到用户点击/点击的链接对应的部分的方法。

HTML

这是我的链接列表:

<ol class="subjects">
    <li><a href="#folderstructure">Folder Structure</a></li>
    <li><a href="#namingconventions">Naming Conventions</a></li>
    <li><a href="#codingstyle">Coding Style</a></li>
    <li><a href="#credits">Credits</a></li>
</ol>

这是我的部分的结构:

<ol class="subjects--sections">
    <li id="folderstructure">Heading...<a href="#top">Top &uarr;</a></li>
    <li id="namingconventions">Heading...<a href="#top">Top &uarr;</a></li>
    <li id="codingstyle">Heading...<a href="#top">Top &uarr;</a></li>
    <li id="credits">Heading...<a href="#top">Top &uarr;</a></li>
</ol>

所以我需要的是将类active添加到相应部分的方式,因此如果点击/点按#folderstructure,那么li将如下所示:

<li id="folderstructure" class="active">Heading...<a href="#top">Top &uarr;</a></li>

如果点击/点按#namingconventions,则li将如下所示:

<li id="namingconventions" class="active">Heading...<a href="#top">Top &uarr;</a></li>

等其他部分,有道理吗?

非常感谢任何帮助。谢谢!

3 个答案:

答案 0 :(得分:2)

你可以这样做:

$('.subjects a').on('click',function(){
   $('.subjects--sections .active').removeClass("active"); // removes active class
   $($(this).attr("href")).addClass("active"); // adds it again
});

DEMO

答案 1 :(得分:1)

这里不需要JavaScript,CSS :target(和:before)应该做你需要的。

答案 2 :(得分:0)

Try it for better efficiency....


$(document).ready( function( ) {
    $('ol.subjects a').on( {
        "click" : function( ) {
                    var sel_href_attr; /* It'll contain clicked anchor tag href attribute valte*/

                    sel_href_attr = $(this).attr("href").slice(1);

                    $('ol.subjects--sections li.active').removeClass('active');
                    /*
                        If you want to remove "class" attribute then you may use below statement 
                        in spite of above jQuery statement
                        $('ol.subjects--sections li.active').removeAttr('class');
                    */    
                    $('ol.subjects--sections li#'+sel_href_attr).addClass('active');
                }
    } );
});
相关问题