如何使用jquery查找包含与前缀匹配的data- *属性的元素 [英] how do I find elements that contain a data-* attribute matching a prefix using jquery
问题描述
我想创建一个选择器来查找具有以字符串开头的属性的元素。此时,我假设这个选择器不存在。
我是否需要扩展选择器功能? James Padolsey 扩展jQuery的选择器功能
I'm want to create a selector to find elements which have attributes starting with a string. At this point, I'm assuming this selector does not exist. Do I need to extend the selector capabilities? Extending jQuery’s selector capabilities by James Padolsey
我需要表达类似于包含前缀选择器[name | =value]的内容,但不是匹配value,而是需要匹配属性的名称,而不是属性的值。
I need to express something like the Attribute Contains Prefix Selector [name|="value"], but instead of matching "value", I need to match against the name of the attribute, and not the value of the attribute.
< tag data-plugin-option1 =val1data-plugin-option2 =val2/>
我想最终得到这样的语法:
$('tag(:attr | = data-plugin)')
应该找到元素标记
,因为它至少有一个以数据开头的元素-plugin
I'd like to end up with a syntax like this:
$('tag(:attr|="data-plugin")')
which should find the element tag
because it has at least one element that starts with data-plugin
推荐答案
好吧,我想我的阅读方式不同了。
Well, I guess I'm reading your question differently.
我读它的方式,你想创建一个自定义选择器,选择具有给定属性名称(或该名称的开头)的元素。
The way I read it, you want to create a custom selector that selects elements that have a given attribute name (or the start of that name).
如果是这样,我认为您需要为每个元素迭代属性
集合。
If so, I think you'd need to iterate of the attributes
collection for each element.
DEMO: http://jsfiddle.net/GgmM7/
$.extend($.expr[':'],{
attrNameStart: function(el,i,props) {
var hasAttribute = false;
$.each( el.attributes, function(i,attr) {
if( attr.name.indexOf( props[3] ) !== -1 ) {
hasAttribute = true;
return false; // to halt the iteration
}
});
return hasAttribute;
}
});
$('img:attrNameStart(data-plugin)')
这篇关于如何使用jquery查找包含与前缀匹配的data- *属性的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!