[英]jQuery selector with data-* attribute
I'm trying to implement a jQuery selector which selects all the elements with data-xy-* attributes. 我正在尝试实现一个jQuery选择器,该选择器选择所有具有data-xy- *属性的元素。 I know how to select elements if we know the complete data attribute:
如果知道完整的data属性,我知道如何选择元素:
$("[data-xy-a]")
will give me all the elements which have a data attribute data-xy-a
$("[data-xy-a]")
将为我提供所有具有数据属性data-xy-a
的元素
My problem is that the element can have any value instead of a
. 我的问题是,该材料可具有任何价值,而不是
a
。 I want something like: 我想要类似的东西:
$("[data-xy-*]")
There is no selector for this (as far as I know) but you can filter them out yourself... (据我所知)没有选择器,但是您可以自己过滤掉它们。
$.expr[':'].dataStartsWith = function (elem, index, not) {
var data = $(elem).data();
return Object.keys(data).some(function (key) {
return key.indexOf(not[3]) === 0;
});
};
$(':dataStartsWith("xy")');
Just bear in mind data attribute names are converted to camelcase in dataset so to match data-xy-z-*
you will need to use $(':dataStartsWith("xyZ")');
只需记住数据属性名称会在数据集中转换为驼峰形,因此要匹配
data-xy-z-*
您将需要使用$(':dataStartsWith("xyZ")');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.