使用jQuery是否可以选择所有href以"ABC"结尾的<a>
链接?
例如,如果我想找到这个链接<a href="http://server/page.aspx?id=ABC">
$('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-...")
$('a[href$="ABC"]:first').attr('title');
这将返回第一个链接的标题,该链接的URL以"ABC"结尾。
$("a[href*='id=ABC']").addClass('active_jquery_menu');
$("a[href*=ABC]").addClass('selected');
如果您不想导入像jQuery这样的大型库来完成这个微不足道的事情,您可以使用内置方法querySelectorAll
。几乎所有用于jQuery的选择器字符串也适用于DOM方法:
const anchors = document.querySelectorAll('a[href$="ABC"]');
或者,如果您知道只有一个匹配的元素:
const anchor = document.querySelector('a[href$="ABC"]');
如果您要搜索的属性值是字母数字组合,通常可以省略属性值周围的引号,例如,在此处,您也可以使用
a[href$=ABC]
但引号更加灵活,通常也更可靠。
$('a').filter(function() { return !this.href || !this.href.match(/ABC/); });
- tvanfossondocument.querySelectorAll('a[href$="ABC"]')
即可实现此功能。 - k-nut