使用 javascript/jquery 遍历包含 HTML 的字符串中的所有标记

Iterating over all tags in a string containing HTML using javascript/jquery

本文关键字:字符串 HTML javascript jquery 遍历 包含 使用      更新时间:2023-09-26

我正在使用富文本编辑器类型控件,这是一个作为jQuery插件编写的。它基本上将 IFrame 插入到页面上,并使其可编辑 - 对于富文本控件来说相当标准。

现在,我要做的是改进一个选项,该选项从文本编辑器中删除所有格式。目前,它正在使用大量正则表达式来完成,快速的谷歌搜索表明这不是正确的方法。我希望允许这种取消格式化的某种程度的灵活性,以便我可以保留某些标签(如段落标签)。

我试图使用DOM解析中内置的jQuery来轻松做到这一点,但我似乎遇到了麻烦。

假设我有一个示例 HTML 字符串:

<Body><p>One <strong>Two</strong> <em>Three</em></p></Body>

我希望取消格式化它,以便删除所有非段落标签。所以,我希望输出是一个字符串,如下所示:

<Body><p>One Two Three</p></Body>

示例代码:

//Some very simple HTML obtained from an editable iframe
var text = '<Body><p>One <strong>Two</strong> <em>Three</em></p></Body>';
var $text = $(text);
//All tags which are not paragraphs
$(':not(p)',$text).each(function() {
    //Replace the tag + content with just content
    $(this).html($(this).text());
});
//I'll be honest, I found this snippet somewhere else on stackoverflow,
//It seems to parse the jquery object back into an HTML string.
var returnVal = "";
$text.each(function(){
    returnVal += $(this).clone().wrap('<p>').parent().html();
});
//Should be equal to '<p>One Two Three</p>'       
return returnVal;

这似乎应该有效,但不幸的是它没有。在上面的例子中,'returnVal' 与输入相同(减去 'body' 标头标签)。我在这里明显做错了什么吗?

替换此行:

$(this).html($(this).text());

。有了这个:

$(this).replaceWith($(this).text());

。它应该有效(至少它在这里有效)。

...snip
// Here's your bug:
$(':not(p)',$text).each(function() {
//  You can't use .html() to replace the content 
//     $(this).html($(this).text());
//   You have to replace the entire element, not just its contents:
    $(this).replaceWith($(this).text());
});
...snip