1

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

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

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

假设我有一个示例 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”标题标签)。有什么我明显做错了吗?

4

2 回答 2

2

替换这一行:

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

... 有了这个:

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

...它应该可以工作(至少在这里可以工作)。

于 2012-06-25T23:01:40.173 回答
1
...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
于 2012-06-25T23:02:23.070 回答