如何使用jQuery选择其href与请求的页面/文件名匹配的超链接的父对象?

如何使用jQuery选择其href与请求的页面/文件名匹配的超链接的父对象?,jquery,Jquery,如何使用jQuery选择其href与请求的页面/文件名匹配的超链接的父对象 我有以下代码 <div> <div class="menu-head"> <a href="empdet.aspx">employees</a> <a href="custdet.aspx">customers</a> </div> <div class="menu-head"> <a href="depdet.aspx

如何使用jQuery选择其href与请求的页面/文件名匹配的超链接的父对象

我有以下代码

<div>
<div class="menu-head">
<a href="empdet.aspx">employees</a>
<a href="custdet.aspx">customers</a>
</div>
<div class="menu-head">
<a href="depdet.aspx">departments</a>
</div>
<div>

我想要一个Jquery来更改与超链接对应的父div的颜色。如果用户正在浏览custdet.aspx,则相应的父div背景应更改为红色

编辑:我有一个方法来检索文件名。我只需要正确的选择器来选择父对象

$(document).ready(function () {
    $('selector-to-get-your-nav a[href^=' + window.location.pathname + ']').parent().css('backgroundColor', '#FF0000');
});
window.location.pathname将在路径前面加一个/,因此可以在URL的开头加一个斜杠,执行
window.location.pathname.slice(1)
,或者将选择器从
href^=
更改为
href~=
,以执行包含搜索而不是等于搜索(或者改为更改其中任何一个)

编辑:没有用于获取父项的选择器。请选择子项,然后使用

window.location.pathname将在路径前面加一个/,因此可以在URL的开头加一个斜杠,执行
window.location.pathname.slice(1)
,或者将选择器从
href^=
更改为
href~=
,以执行包含搜索而不是等于搜索(或者改为更改其中任何一个)


编辑:没有选择器来获取父项。您选择子项,然后使用

我在两个多小时前试图发布此内容,但我的互联网死机。它刚刚恢复,因此我将其添加到列表中

您可以使用
document.location.pathname
获取当前路径,从“/”上的
split()
pop()
结果数组的末尾获取文件名:

// get the current filename
var file = document.location.pathname.split("/").pop();

// get the parent of a matching hyperlink
var lPar = $('#menu-head > a[href="'+file+'"]').parent();

旁注:在您的示例中,您有两个具有相同id(菜单头)的
div
元素。重复id在同一页面上无效,如果您不使其唯一,则将遇到问题。

我在两个多小时前试图发布此内容,但我的internet已死机。它刚刚恢复,因此我将其添加到列表中

您可以使用
document.location.pathname
获取当前路径,从“/”上的
split()
pop()
结果数组的末尾获取文件名:

// get the current filename
var file = document.location.pathname.split("/").pop();

// get the parent of a matching hyperlink
var lPar = $('#menu-head > a[href="'+file+'"]').parent();

旁注:在您的示例中,有两个id相同的
div
元素(菜单头)。重复ID在同一页上无效,如果不使其唯一,您将遇到问题。

这可能不仅仅是一个
/
。我打算使用
document.location.pathname.slice(document.location.pathname.lastIndexOf('/')+1)建议类似的内容
而不是
window.location.pathname
我使用以下代码查找路径。var sPath=window.location.pathname;var sPage=sPath.substring(sPath.lastIndexOf('/')+1)@drs9222:抱歉..我认为他的链接是绝对的。这取决于他喜欢如何做他的链接。如果他有一个链接作为
foo/bar/index.html
,那么你的例子就不起作用了…摇摆和迂回:)它可能不仅仅是
/
。我打算使用
document.location.pathname.slice来建议类似的东西(document.location.pathname.lastIndexOf('/')+1)
而不是
window.location.pathname
我使用以下代码查找路径。var sPath=window.location.pathname;var sPage=sPath.substring(sPath.lastIndexOf('/')+1)@drs9222:抱歉..我认为他的链接是绝对的。这取决于他喜欢如何做他的链接。如果他有一个链接为
foo/bar/index.html
,那么你的例子就不起作用了…秋千和环形交叉口:)这就是我们要找的。非常感谢安迪:)这就是我们要找的。非常感谢安迪:)