2012-06-26 72 views
2

所以,如果我調用該函數:換行符返回標籤的文本價值和附加到每個標籤

$("#item").text() 

這個HTML代碼:

<div id="item"> 
<pre><span class="cm-tag">&lt;html&gt;</span></pre><pre><span class="cm-tab"> </span>asdf</pre><pre><span class="cm-tag">&lt;/html&gt;</span></pre> 
</div> 

返回:

'<html> asdf</html>' 

我想要它回來:

'<html> 
    asdf 
</html>' 

基本上,我需要在每個<pre>標記後面添加一個新行......我該怎麼做?

回答

1

可能的解決方案,讓每個前的文本,並與新線加入他們:

var text = $("#item pre").map(function(){ 
    return $(this).text(); 
}).get().join('\n'); 

這裏是的jsfiddle:http://jsfiddle.net/uGGFe/

+0

就像我不希望它們通過'\ n's'連接在一起,我希望它們被加入,就好像你在按壓輸入javascript變量一樣......如果這樣做有道理 – maxhud

+0

這將返回:「 asdf」 – maxhud

+1

@maxhud '\ n'被稱爲[newline](http://en.wikipedia.org/wiki/Newline#In_programming_languages)字符,可用於許多語言ges包含c,javascript,python和其他許多表達式,就像「你按下回車鍵」一樣。編輯我的答案與工作解決方案的jsfiddle的鏈接。 – Trevor

0

你的另一個選擇:

var clone = $("#item").clone(); //create a clone we can manipulate 
clone.find('pre').after('\n'); //stick new lines in after <pre> tags 
alert(clone.text());   //behold the alert glory 

http://jsfiddle.net/SrV9c/1/

0
var text = ''; 
$("#item pre").map(function(i, el) { 
    return $(el).text().replace(/\s/g, '') 
}).each(function(i, val) { 
    if (i == 0) 
     text += val.concat('\n\t'); 
    else 
     text += val.concat('\n'); 
}); 

Working sample

+0

@maxhud請檢查我的答案和演示 – thecodeparadox

0

因爲jQuery搜索匹配HTML元素使用正則表達式,當正則表達式匹配的內容先刪除 「\ r \ n」,所以你看到的內容沒有 「\ r \ n」 個

+1

我不認爲這回答了這個問題。 – Thomas