How to remove all Attributes by attribute name starts with

久未见 提交于 2020-01-03 04:55:33

问题


I would like to remove all the attributes that attribute name starts with 'data-val' in the fields that has a class 'read-only-state'

 jQuery("[data-val^='tr']" )  

This will give attribute 'data-val' value that starts with 'tr'

But i need to remove all the attributes that starts with 'data-val' in the matched elements.

How can i do it?


回答1:


You can use vanilla javascript's attributes for this:

$('.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]);
   }
});


来源:https://stackoverflow.com/questions/14731439/how-to-remove-all-attributes-by-attribute-name-starts-with

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