根据部分属性查找HTML [英] Find HTML based on partial attribute
问题描述
有没有办法使用javascript(特别是jQuery)来查找基于部分属性 name 的元素?
Is there a way with javascript (particularly jQuery) to find an element based on a partial attribute name?
我不是在寻找对于找到这些链接中引用的部分属性值的任何选择器:
I am not looking for any of the selectors that find partial attribute values as referenced in these links:
- 以开头[name ^ =value]
- 包含前缀 [name | =value]
- 包含 [name * =value]
- 包含单词 [name~ =value]
- 以结尾[name $ =value]
- 等于 [name =value]
- 不等于 [name!=value]
- 以开头[name ^ =value]
- starts with [name^="value"]
- contains prefix [name|="value"]
- contains [name*="value"]
- contains word [name~="value"]
- ends with [name$="value"]
- equals [name="value"]
- not equal [name!="value"]
- starts with [name^="value"]
但更多的内容
<div data-api-src="some value"></div>
<div data-api-myattr="foobar"></div>
和
$("[^data-api]").doSomething()
查找任何具有以data-api开头的属性的元素。
to find any element that has an attribute that starts with "data-api".
推荐答案
不确定你在寻找什么,但只花了几分钟写这个:
Not sure what it is you're looking for, but just spent a few minutes writing this:
$.fn.filterData = function(set) {
var elems=$([]);
this.each(function(i,e) {
$.each( $(e).data(), function(j,f) {
if (j.substring(0, set.length) == set) {
elems = elems.add($(e));
}
});
});
return elems;
}
使用方式如下:
$('div').filterData('api').css('color', 'red');
并且会匹配任何具有数据属性的元素,例如 data-api- *
,你可以扩展和修改它以包含更多选项等,但现在它只搜索数据属性,只匹配'以'开头',但至少它很容易使用?
And will match any elements with a data attribute like data-api-*
, and you can extend and modify it to include more options etc. but of right now it only searches for data attributes, and only matches 'starts with', but at least it's simple to use ?
这篇关于根据部分属性查找HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!