Wildcards in HTML5 data attributes

▼魔方 西西 提交于 2019-11-28 13:49:48

You can create a custom pseudoclass to e.g. match attribute names against a regexp: http://jsfiddle.net/hN6vx/.

jQuery.expr.pseudos.attr = $.expr.createPseudo(function(arg) {
    var regexp = new RegExp(arg);
    return function(elem) {
        for(var i = 0; i < elem.attributes.length; i++) {
            var attr = elem.attributes[i];
            if(regexp.test(attr.name)) {
                return true;
            }
        }
        return false;
    };
});

Usage:

$(":attr('^data-')")

Because JQuery relies heavily on XPath, and XPath does not support wildcard attribute selection - it is not possible without the overhead you're looking to avoid.

There's always the possibility of creating your own selector, just to keep things clean:

//adds the :dataValidate selector
$.extend($.expr[':'],{
    dataValidate: function(obj){
        var i,dataAttrs=$(obj).data()
        for (i in dataAttrs) {
                if (i.substr(0,8)=='validate') return true;
        }
        return false;
    }
})

Which will allow you to use :dataValidate in your normal jQuery selectors:

$(".element:dataValidate .etc")

Working JSFiddle: http://jsfiddle.net/rZXZ3/

You could loop over the atributes:

$('.element').each(function() {
  $.each(this.attributes, function(i, att){
     if(att.name.indexOf('data-validate')==0){
         console.log(att.name);
     }
  });
});

You can use filter method and dataset object:

Allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

$("input").filter(function(){
    var state = false;
    for (i in this.dataset) 
        if (i.indexOf('validate') > -1) state = true;

    return state             
})​

http://jsfiddle.net/Pxpfa/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!