簡體   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