具有以字符串开头的属性的元素的jQuery选择器
问题描述:
我需要选择所有具有以给定前缀开头的属性的元素-请注意,我所说的是属性名称, not 值.例如:
I need to select all elements, which have an attribute starting with a given prefix - note I am talking about the attribute name, not value. For example:
<div data-abc-name="value">...</div>
<a href="..." data-abc-another="something">...</a>
<span data-nonabc="123">...</span>
在上面的HTML中,我需要获取所有具有以data-abc-
开头的属性的元素-即div
和a
.
In the above HTML, I need to get all elements that have an attribute starting with data-abc-
- that is, the div
and the a
.
我该怎么做?
答
您可以在ES6中这样做:
You can do it like this by ES6:
$('*').filter(function() {
for (attr of this.attributes)
if (attr.name.startsWith("data-abc"))
return this;
});