jQuery 查找具有精确 href 的锚标记

发布于 2024-12-14 04:05:22 字数 310 浏览 3 评论 0原文

我使用以下代码来查找具有匹配 href URL 的锚标记。目前,它将返回链接到所请求 URL 的锚点,例如。 /images 以及该 url 子文件夹的任何链接,例如。 /images/recent。如果我只要求 /images,我希望它只返回第一个。

$menuChildren = $menuChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');

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.

$menuChildren = $menuChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷…雨湿花 2024-12-21 04:05:22

您正在使用 ^=,即 Attribute Starts-With 选择器 。顾名思义,它匹配其值匹配字符串开头的属性。相反,请使用 =,即需要完全匹配的 属性等于选择器

$menuChildren = $menuChildren.has('a[href="'+url+'"]');

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:

$menuChildren = $menuChildren.has('a[href="'+url+'"]');
愁以何悠 2024-12-21 04:05:22

如果您想完全匹配 href,请使用 [href=...] 版本

$menuChildren = $('a[href="' + relativeUrl + '"]');

If you want to match the href exactly then use the [href=...] version

$menuChildren = $('a[href="' + relativeUrl + '"]');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文