【发布时间】:2010-09-23 04:03:03
【问题描述】:
是否可以使用jQuery 选择所有href 以“ABC”结尾的<a> 链接?
比如我想找到这个链接<a href="http://server/page.aspx?id=ABC">
【问题讨论】:
是否可以使用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').filter(function() { return !this.href || !this.href.match(/ABC/); });
document.querySelectorAll('a[href$="ABC"]') 来实现这一点。
$('a[href$="ABC"]:first').attr('title');
这将返回 URL 以“ABC”结尾的第一个链接的标题。
【讨论】:
$("a[href*='id=ABC']").addClass('active_jquery_menu');
【讨论】:
ABC 碰巧引用了一个 ID 时,您的答案才是正确的。
$("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]
但引号更灵活,generally more reliable。
【讨论】: