如何按属性名称删除所有属性

Mur*_*san 0 javascript jquery jquery-selectors

我想在具有类'只读状态'的字段中删除属性名称以'data-val'开头的所有属性

 jQuery("[data-val^='tr']" )  
Run Code Online (Sandbox Code Playgroud)

这将给出以'tr'开头的属性'data-val'值

但我需要删除匹配元素中以'data-val'开头的所有属性.

我该怎么做?

Bea*_*rtz 7

你可以使用vanilla javascript attributes:

$('.read-only-state').each(function() {
   // get the native attributes object
   var attrs = this.attributes;
   var toRemove = [];
   // cache the jquery object containing the element for better performance
   var element = $(this);

   // iterate the attributes
   for (attr in attrs) {
     if (typeof attrs[attr] === 'object' && 
         typeof attrs[attr].name === 'string' && 
         (/^data-val/).test(attrs[attr].name)) {
       // Unfortunately, we can not call removeAttr directly in here, since it
       // hurts the iteration.
       toRemove.push(attrs[attr].name);
     }
   }

   for (var i = 0; i < toRemove.length; i++) {
     element.removeAttr(toRemove[i]);
   }
});
Run Code Online (Sandbox Code Playgroud)