jQuery jQuery使用精确的href查找锚标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8040424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery find anchor tag with exact href
提问by jetlej
I'm using the following code to find anchor tags with a matching href URL. Currently it will return anchors linking to the requested URL, eg. /images
AND any links to subfolders of that url, eg. /images/recent
. I would like it to only return the first if I'm only asking for /images
.
我正在使用以下代码查找具有匹配 href URL 的锚标记。目前它将返回链接到请求的 URL 的锚点,例如。/images
以及指向该网址子文件夹的任何链接,例如。/images/recent
. 如果我只要求/images
.
$menuChildren = $menuChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');
回答by meagar
You're using ^=
, the Attribute Starts-With selector. As its name suggests, it matches attributes whose values start withthe match string. Instead, use =
, the Attribute Equals selectorwhich requires an exact match:
您正在使用^=
的属性开始,随着选择。顾名思义,它匹配值以匹配字符串开头的属性。相反,使用=
的属性等于选择需要精确匹配:
$menuChildren = $menuChildren.has('a[href="'+url+'"]');
回答by JaredPar
If you want to match the href exactly then use the [href=...]
version
如果您想完全匹配 href 则使用[href=...]
版本
$menuChildren = $('a[href="' + relativeUrl + '"]');