删除基于白名单的元素的所有属性 [英] Remove all attributes of a element based on a whitelist

查看:99
本文介绍了删除基于白名单的元素的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除某些元素上设置的所有属性(使用香草JS或jQuery),除了一些手动选择的属性.可以说我有一张图片:

I need to remove all attributes set on certain elements (using vanilla JS or jQuery), except for a few manually selected ones. Lets say I have an image:

<img hspace="4" border="1" vspace="4" src="someimage.jpg" alt="somealt" />

我希望这是结果:

<img src="someimage.jpg" alt="somealt" />

我能想到的唯一方法是对每个单独的属性进行.removeAttr().但是问题在于,有时元素具有的属性在W3C规范中不存在.我要删除未列入白名单的所有其他属性.

The only way I could think of is to .removeAttr() every single attribute. But the problem is that some times elements have attributes that are don't exist in the W3C specification. I want to remove all other attributes that are not whitelisted.

您将如何做?

推荐答案

以下是对attributes列表进行迭代的解决方案.

Here's a solution that iterates over the attributes list.

我实际上只是将其值设置为""(空字符串),因为出于某些原因,removeAttribute()在到达border属性时会失败.正在调查...

I'm actually only setting its value to "" (empty string), because for some reason, removeAttribute() fails when it gets to the border attribute. Investigating...

尝试一下:

var whitelist = ["src","alt"];

$('img').each(function() {
    var attributes = this.attributes;
    var i = attributes.length;
    while( i-- ) {
        var attr = attributes[i];
        if( $.inArray(attr.name,whitelist) == -1 )
            this.removeAttributeNode(attr);
    }
});​

这篇关于删除基于白名单的元素的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆