2011-03-30 95 views
0

我需要導入一個輸入文本域值地帶標籤,更換裏面的textarea

使用jQuery

有啥做到這一點的最好辦法某些格式的HTML文本換行BR? 我首先猜測關閉我需要更換
然後去掉其餘部分(粗體,斜體,圖像等)

回答

2

在我的第一響應我沒有看到你想保留換行符,所以這是一個更好的版本。它用一個不太可能的字符串%% br %%替換br,然後在最後用新行替換它們(\ n)。因此,如果該字符串實際出現在文本中,它將被替換爲一個新行。您可以將其更改爲您喜歡的任何內容,只需將其設置爲不太可能在文本中遇到的內容即可。

<script> 

function removeMarkup(m) { 
    var d = document.createElement('div'); 
    d.innerHTML = m; 
    var c = 0; 

    // Make brString something that should never appear in the text 
    // and has no special meaning in a RegExp 
    var brString = '%%br%%' 
    var re = new RegExp('\\s*' + brString + '\\s*','g'); 

    function getTextWithReturns(node) { 

    var tag = node.tagName && node.tagName.toLowerCase(); 
    var nodes = node.childNodes; 
    var type = node.nodeType; 
    var s = ''; 

    // Deal with br 
    if (tag == 'br') { 
     return brString; 
    } 

    if (nodes && nodes.length) { 
     for (var i=0, iLen=nodes.length; i<iLen; i++) { 
     s += getTextWithReturns(nodes[i]); 
     } 
    } else if (type == 3 || type == 4) { 
     s += node.nodeValue 
    } 
    return s; 
    } 
    return reduceWhitespace(getTextWithReturns(d)).replace(re,'\n'); 
} 

function reduceWhitespace(s) { 
    return s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g,' '); 
} 

</script> 

<div id="d0">some text <i>more</i> text 
    <p>Here is a paragraph with some <b>bold</b> and <i>italic</i> text, plus a <span>span</span> and a line break break break<br> about there.</p> 
    <p>Here is another paragraph with some <b>bold</b> and <i>italic</i> text, plus plus a <span>span</span> and a line break <br> here.</p> 
</div> 

<form> 
<textarea id="ta0" rows="10" cols="50"></textarea> 
<button type="button" onclick=" 
    var ta = document.getElementById('ta0'); 
    var div = document.getElementById('d0'); 
    ta.value = removeMarkup(div.innerHTML); 
">Set value</button><input type="reset"> 
</form> 
0
$("#my_textarea").change(function(){ 
    var cleanText = $("<span />").html(this.value); 
    this.value = cleanText.text(); 
}); 

實施例:http://jsfiddle.net/6WbXN/

+0

innerText是一個專有的Microsoft屬性,不受所有瀏覽器支持。 (大致)相同的W3C DOM屬性是textContent。但是,空格和換行符的處理方式不同,應使用某種正則表達式或替換來規範化它。 – RobG 2011-03-30 04:24:50

+0

哪一個處理換行符的方式不同? 'textContent'或'innerText'?我的編輯修復了跨瀏覽器問題嗎? – mattsven 2011-03-30 04:33:48

+0

他們彼此不同。順便提一句,jQuery既不使用它,它在子節點上遞歸尋找文本節點並連接它們的值。這是一個合理的策略,但通常比使用textContent或innerText(如果可用)慢。 – RobG 2011-03-30 04:53:18