How to get the ID of an active link

↘锁芯ラ 提交于 2020-01-15 10:15:24

问题


I'd like to display the ID of the active link in my navbar through an alert, but I'm not sure how to do this with my current Bootstrap 3 classes.

I was thinking of something like

alert( $('li').hasClass( "active" ).attr('id') );

but sadly that doesn't work.

Bootply

HTML:

<div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">

                <div class="collapse navbar-collapse navHeaderCollapse">

                    <ul class="nav navbar-nav navbar-right">

                        <li class = "active"><a id = "tab1" href = "#" >Link1</a></li>
                        <li><a id="tab2" href = "#">Link2</a></li>
                        <li><a id = "tab3" href = "#" >Link3</a></li>

                    </ul><!-- END: "collapse navbar-collapse navHeaderCollapse" -->
                </div><!-- END: "container" -->
            </div><!-- END: "container" -->
</div><!-- END: "navbar navbar-inverse navbar-fixed-top" -->

回答1:


You need to find the child of the li not the li itself, also why not use the class in the selector instead of using hasClass:

alert($('li.active a').attr('id'));

See Demo




回答2:


Try this

$(function(){
  alert( $('li.active a').prop('id') );
});


来源:https://stackoverflow.com/questions/25276016/how-to-get-the-id-of-an-active-link

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