如何获取url参数并添加活动类witt javascript/jquery

How to get url parameter and add active class witt javascript/jquery?

本文关键字:活动 添加 witt javascript jquery 参数 何获取 获取 url      更新时间:2023-11-30

我的链接是这样的:

index.php
index.php?do=that
index.php?do=this

我目前的javascript代码是这样的:

var url = window.location.pathname, 
    urlRegExp = new RegExp(url.replace(/'/$/,'') + "$");
    console.log(url);
    $('.nav-link').each(function(){
        if(urlRegExp.test(this.href.replace(/'/$/,''))){
            $(this).addClass('active');
        }
    });
});

所以有了这个代码,即使我在index.php?do=this控制台,日志也会告诉我/path/index.php

我想我需要更改var url = window.location.pathname线路,但我做不到。

我应该如何改进我的代码?SO中有很多相似的问题,但不是同一个。

我感谢你的帮助。

在PHP中,您可以从get数组中获取URL参数。$_GET['do']或尝试打印$_GET。此数组将打印所有URL参数。希望这能有所帮助!