返回标签的文本值,并在每个标签后附加换行符

return the text value of tags and append a line break to each tag

本文关键字:标签 换行符 文本 返回      更新时间:2023-09-26

所以如果我调用这个函数:

$("#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>标签之后换一行......我该怎么做?

一个可能的解决方案,获取每个 pre 的文本并用新行连接它们:

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

这是jsfiddle:http://jsfiddle.net/uGGFe/

另一个选择:

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/

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');
});

工作样品

因为jQuery搜索匹配htmlElement使用正则表达式,当正则表达式匹配内容时先删除"''r'",所以你看到的内容没有"''r'"