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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 09:54:42  来源:igfitidea点击:

jQuery find anchor tag with exact href

jqueryanchorhref

提问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. /imagesAND 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 + '"]');