688

是否可以使用jQuery选择所有<a>href 以“ABC”结尾的链接?

例如,如果我想找到这个链接<a href="http://server/page.aspx?id=ABC">

4

5 回答 5

1603
   $('a[href$="ABC"]')...

选择器文档可以在http://docs.jquery.com/Selectors找到

对于属性:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
于 2008-11-20T00:26:13.230 回答
22
$('a[href$="ABC"]:first').attr('title');

这将返回 URL 以“ABC”结尾的第一个链接的标题。

于 2010-06-24T21:01:47.333 回答
16
$("a[href*='id=ABC']").addClass('active_jquery_menu');
于 2012-02-29T08:27:55.580 回答
6
$("a[href*=ABC]").addClass('selected');
于 2012-09-20T14:53:27.400 回答
4

万一您不想导入像 jQuery 这样的大库来完成如此琐碎的事情,您可以使用内置方法querySelectorAll。几乎所有用于 jQuery 的选择器字符串也适用于 DOM 方法:

const anchors = document.querySelectorAll('a[href$="ABC"]');

或者,如果您知道只有一个匹配元素:

const anchor = document.querySelector('a[href$="ABC"]');

如果您要搜索的值是字母数字,您通常可以省略属性值周围的引号,例如,在这里,您也可以使用

a[href$=ABC]

但报价更灵活,通常更可靠

于 2019-05-21T07:57:07.563 回答