var whitelist = ['a','div','img', 'span'];
给定一段 HTML 代码,我想使用 JQuery 遍历每个标签
然后,如果该标签不在我的白名单中,删除它及其所有子标签。
现在应该清理最终字符串。
我该怎么做?
顺便说一下,这是我当前删除特定标签的代码(但我决定改用白名单)
var canvas = '<div>'+canvas_html+'</div>';
var blacklist = ['script','object','param','embed','applet','app','iframe',
'form','input', 'link','meta','title','input','button','textarea'
'head','body','kbd'];
blacklist.forEach(function(r){
$(canvas).find(r).remove();
});
canvas_html = $(canvas).get('div').html();
最佳答案
试试这个:
var whitelist = ['a','div','img', 'span'];
var output = $('<div>'+canvas_html+'</div>').find('*').each(function() {
if($.inArray(this.nodeName.toLowerCase(), whitelist)==-1) {
$(this).remove();
}
}).html();
// output contains the HTML with everything except those in the whitelist stripped off
关于javascript - 给定一串 html 代码,我如何遍历每个标记并删除不在我的白名单中的标记(在 JQuery 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8800019/