【问题标题】:Get url path and add class active on li获取 url 路径并在 li 上添加活动类
【发布时间】:2012-07-31 03:45:20
【问题描述】:

我尝试获取 url 路径,然后在 li 上添加活动类 例子: www.mysite.com/?p=xxxx

x 会根据用户点击的链接而变化

我试过了:

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

但什么也没发生。我做错了什么?

【问题讨论】:

  • 首先你可以使用window.location.search,跳过正则表达式部分

标签: jquery url path href addclass


【解决方案1】:

这行得通!

$(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");

        }

    });

});

【讨论】:

    【解决方案2】:

    您可以使用ends with 属性选择器:

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

    这将获得 href 属性以pid 结尾的链接(在本例中为 1885)。

    如果您有 2 个以相同字符串结尾的值(例如 p=1885 和 p=11885),则会导致问题。

    【讨论】:

    • 你能再解释一下吗?我对jq不太熟练
    • 那我得为每个链接制作一个?
    • 不,只有一次,但您必须将第一行替换为 p 的当前值。我建议使用document.location.search 并在其上运行正则表达式。
    【解决方案3】:

    如何更改类名并使用 PHP 和 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>';
        }
    
    ?>
    

    例如,在“www.mysite.com/?p=1888”上将打印:

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

    它将为类名为“p_1888”的 HTML 添加“活动”类。例如:

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

    还解释了here。

    【讨论】:

    • 好主意,但该网站是用 aspx 编写的。而且我在aspx方面没有经验
    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 2013-07-02
    • 2014-02-23
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    相关资源
    最近更新 更多