繁体   English   中英

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

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

我正在使用富文本编辑器类型控件,它是一个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM