Dav*_*ing 36 javascript jquery
是否可以使用jQuery一次删除所有属性?
<img src="example.jpg" width="100" height="100">
Run Code Online (Sandbox Code Playgroud)
至
<img>
Run Code Online (Sandbox Code Playgroud)
我试着$('img').removeAttr('*');
没有运气.任何人?
小智 59
一个不需要JQuery的简单方法:
while(elem.attributes.length > 0)
elem.removeAttribute(elem.attributes[0].name);
Run Code Online (Sandbox Code Playgroud)
cle*_*tus 49
更新:以前的方法适用于IE8,但不适用于IE8兼容模式和以前版本的IE.所以这是一个版本,它使用jQuery来删除属性,因为它可以更好地完成它:
$("img").each(function() {
// first copy the attributes to remove
// if we don't do this it causes problems
// iterating over the array we're removing
// elements from
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// now use jQuery to remove the attributes
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
Run Code Online (Sandbox Code Playgroud)
当然你可以用它来插件:
jQuery.fn.removeAttributes = function() {
return this.each(function() {
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
}
Run Code Online (Sandbox Code Playgroud)
然后做:
$("img").removeAttributes();
Run Code Online (Sandbox Code Playgroud)
小智 16
单行,不需要 jQuery:
[...elem.attributes].forEach(attr => elem.removeAttribute(attr.name));
Run Code Online (Sandbox Code Playgroud)
jQuery.fn.removeAttributes
您可以扩展 jQuery 的现有.removeAttr()
方法,使其接受零参数以从集合中的每个元素中删除所有属性,而不是创建一个新的(在已接受的答案中演示):
var removeAttr = jQuery.fn.removeAttr;
jQuery.fn.removeAttr = function() {
if (!arguments.length) {
this.each(function() {
// Looping attributes array in reverse direction
// to avoid skipping items due to the changing length
// when removing them on every iteration.
for (var i = this.attributes.length -1; i >= 0 ; i--) {
jQuery(this).removeAttr(this.attributes[i].name);
}
});
return this;
}
return removeAttr.apply(this, arguments);
};
Run Code Online (Sandbox Code Playgroud)
现在您可以.removeAttr()
不带参数调用以从元素中删除所有属性:
$('img').removeAttr();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
45542 次 |
最近记录: |