简体   繁体   中英

jQuery selector with data-* attribute

I'm trying to implement a jQuery selector which selects all the elements with data-xy-* attributes. I know how to select elements if we know the complete data attribute:

$("[data-xy-a]") will give me all the elements which have a data attribute data-xy-a

My problem is that the element can have any value instead of 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")');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM