jQuery 选择 <a> 其中 href 以某个字符串结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/303956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select <a> which href ends with some string
提问by Aximili
Is it possible using jQuery to select all <a>
links which href ends with "ABC"?
是否可以使用 jQuery 选择所有<a>
以“ABC”结尾的 href 链接?
For example, if I want to find this link <a href="http://server/page.aspx?id=ABC">
例如,如果我想找到这个链接 <a href="http://server/page.aspx?id=ABC">
回答by tvanfosson
$('a[href$="ABC"]')...
Selector documentation can be found at http://docs.jquery.com/Selectors
选择器文档可以在http://docs.jquery.com/Selectors找到
For attributes:
对于属性:
= 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-...")
回答by Ash
$('a[href$="ABC"]:first').attr('title');
This will return the title of the first link that has a URL which ends with "ABC".
这将返回具有以“ABC”结尾的 URL 的第一个链接的标题。
回答by Sumit
$("a[href*='id=ABC']").addClass('active_jquery_menu');
回答by Ganesh Anugu
$("a[href*=ABC]").addClass('selected');
回答by CertainPerformance
Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll
instead. Almost all selector strings used for jQuery work with DOM methods as well:
以防万一您不想导入像 jQuery 这样的大库来完成这些微不足道的事情,您可以改用内置方法querySelectorAll
。几乎所有用于 jQuery 的选择器字符串也适用于 DOM 方法:
const anchors = document.querySelectorAll('a[href$="ABC"]');
Or, if you know that there's only one matching element:
或者,如果您知道只有一个匹配元素:
const anchor = document.querySelector('a[href$="ABC"]');
You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use
如果您要搜索的值是字母数字,则通常可以省略属性值周围的引号,例如,在这里,您也可以使用
a[href$=ABC]
but quotes are more flexible and generally more reliable.
但报价更灵活,通常更可靠。