2012-06-26 71 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