如何使用位置.Href代替location.pathname

How to use location.href instead of location.pathname

本文关键字:location pathname 代替 Href 何使用 位置      更新时间:2023-09-26

我的Javascript函数是这样的:

       function markActiveLink() {
            var path = location.pathname;
            var home = "/";
            if (path == home)
                return
            $("a[href='" + [path || home] + "']").parents("li").each(function () {
                $(this).removeClass('menu_item');
                $(this).addClass("menu_item_active");
            });
        }

但是我想使用document.location.href而不是location.pathname来查找链接。我试过只是改变它,但然后功能不工作在所有->我的链接都没有被选中。

我的一些链接的代码看起来像这样:

 <ul>
            <li><a href="<%=System.Configuration.ConfigurationManager.AppSettings("VirtualDirectory").ToString()%>User/UserOrder.aspx?id=<%=pe.UserId%>&type=NMO">
                <%=Me.GetLocalResourceObject("NMOrders.Text")%>
            </a></li>
            <li><a href="<%=System.Configuration.ConfigurationManager.AppSettings("VirtualDirectory").ToString()%>User/UserOrder.aspx?id=<%=pe.UserId%>&type=MO">
                <%=Me.GetLocalResourceObject("MOrders.Text")%>
            </a></li>
            <li><a href="<%=System.Configuration.ConfigurationManager.AppSettings("VirtualDirectory").ToString()%>User/UserPage.aspx?id=<%=pe.UserId%>">
                <%=Me.GetLocalResourceObject("UserPage.Text")%>
            </a></li>
        </ul>

在页面上这些链接源是这样的:

<ul>
                <li><a href="/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=NMO">
                    User Orders NMO
                </a></li>
                <li><a href="/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO">
                    User Orders MO
                </a></li>
                <li><a href="/App/User/UserPage.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1">
                    User Page
                </a></li>
</ul>

和这些链接的位置值。pathname将只有/App/User/UserOrder.aspx,我需要检查整个链接。这就是为什么我尝试使用位置。href。

位置。例如:http://localhost/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO然后是位置。路径名是:/App/User/UserOrder.aspx

任何帮助在这里非常感激!

使用字符串连接来包含查询:

var path = location.pathname + location.search;

明显位置。Href包含不在链接中的文本(协议和主机名:"http://localhost/")。

你要么需要从位置中删除这个。

只有location.hrefwindow.location.href而不是document.location.href

试试这个

function markActiveLink() {
            var path = location.pathname;
            var home = "/", $this, href, locationHref = location.href.toLowerCase();
            if (path == home)
                return;
            $("ul li").removeClass('menu_item');
            $("ul a").each(function () {
                $this = $(this);
                href = $this.attr("href").toLowerCase();
                if(locationHref.substring(locationHref.length - href.length) == href) 
                {
                  $this.closest("li").addClass("menu_item_active");
                  return false;
                } 
            });
        }