最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the ID of an active link - Stack Overflow

programmeradmin2浏览0评论

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

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" -->
Share Improve this question asked Aug 13, 2014 at 0:02 michaelmichael 1676 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

Try this

$(function(){
  alert( $('li.active a').prop('id') );
});
发布评论

评论列表(0)

  1. 暂无评论