Get url path and add class active on li

2019-08-30 18:47发布

I try to grab the url path and then add active class on li example: www.mysite.com/?p=xxxx

the x will change depending on which link the user clicks on

I tried this:

<ul class="top_menu">
<li class="tider"><a href="/?p=1884">Åbningstider</a></li>
<li class="butikker"><a href="/?p=1885">Butikker</a></li>
<li class="sker"><a href="/?p=1886">Det sker</a></li>
<li class="nyhedsbrev"><a href="/?p=1887">Nyhedsbrev</a></li>
<li class="vej"><a href="/?p=1888">Find vej</a></li>
</ul>

var text = window.location.href.match(/http:\/\/www\.mysite\.com\/(.+)/)[1].replace(/_/g,' ');
$("#nav li").filter(function() {
  return $.text([this]) == text;
}).addClass("active");

but nothing happens. What im i doing wrong?

3条回答
贼婆χ
2楼-- · 2019-08-30 19:21

You could use the ends with attribute selector:

var pid = '1885'; //Get the current value of p
$('#nav li a[href$="'+pid+'"]').parent().addClass('active');

This will get the link where the href attribute ends in pid (in this case 1885).

That will lead to problems if you have 2 values that end in the same string (like p=1885 and p=11885).

查看更多
成全新的幸福
3楼-- · 2019-08-30 19:34

What about changing class names and use PHP and jQuery:

<?php

if(isset($_GET['p'])) {

    echo '<script type="text/javascript">
    $(document).ready(function(){';

    $from_url = $_GET['p'];

    echo '
    $(\'p_' . $from_url . '\').addClass(\'active\');
        });
    </script>';
    }

?>

For example, at "www.mysite.com/?p=1888" the above will print:

<script type="text/javascript">
$(document).ready(function(){
    $('.p_1888').addClass('active');
    });
</script>

It will add class "active" for the HTML with class name "p_1888". For example:

<li class="p_1888"><a href="/?p=1888">Find vej</a></li>

Also explained here.

查看更多
干净又极端
4楼-- · 2019-08-30 19:44

This works!

$(document).ready(function(){

    var full_path = location.href.split("#")[0];

    $(".top_menu li a").each(function(){

        var $this = $(this);

        if($this.prop("href").split("#")[0] == full_path) {

            $(this).parent().addClass("active");

        }

    });

});
查看更多
登录 后发表回答