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和该URL的子文件夹的任何链接,例如。 /图像/近。如果我只是要求/图像,我希望它只返回第一个。
$menuChildren = $menuChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');
2 个解决方案
#1
25
You're using ^=
, the Attribute Starts-With selector. As its name suggests, it matches attributes whose values start with the match string. Instead, use =
, the Attribute Equals selector which requires an exact match:
您正在使用^ =,Attribute Starts-With选择器。顾名思义,它匹配其值以匹配字符串开头的属性。相反,使用=,属性等于选择器,它需要完全匹配:
$menuChildren = $menuChildren.has('a[href="'+url+'"]');
#2
12
If you want to match the href exactly then use the [href=...]
version
如果要精确匹配href,请使用[href = ...]版本
$menuChildren = $('a[href="' + relativeUrl + '"]');
#1
25
You're using ^=
, the Attribute Starts-With selector. As its name suggests, it matches attributes whose values start with the match string. Instead, use =
, the Attribute Equals selector which requires an exact match:
您正在使用^ =,Attribute Starts-With选择器。顾名思义,它匹配其值以匹配字符串开头的属性。相反,使用=,属性等于选择器,它需要完全匹配:
$menuChildren = $menuChildren.has('a[href="'+url+'"]');
#2
12
If you want to match the href exactly then use the [href=...]
version
如果要精确匹配href,请使用[href = ...]版本
$menuChildren = $('a[href="' + relativeUrl + '"]');