如何在换行符上插入 javascript textNode 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8147376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a javascript textNode element on a newline
提问by Anthony
I insert several textNodes in javascript, and can't figure out how to separate them with carriage returns. I've tried putting "\n", "\r", and "
" but none of them work
我在 javascript 中插入了几个 textNodes,但不知道如何用回车分隔它们。我试过把“\n”、“\r”和“
”放在一起,但它们都不起作用
var textNode = document.createTextNode("Node on line 1");
element.appendChild(textNode);
textNode = document.createTextNode("Node on line 2");
element.appendChild(textNode);
I want this to appear as:
我希望它显示为:
Node on line 1
第 1 行的节点
Node on line 2
第 2 行的节点
NOT
不是
Node on line 1Node on line2
第 1 行的节点第 2 行的节点
Any tips on how I can accomplish this ?
关于我如何做到这一点的任何提示?
回答by Selvakumar Ponnusamy
Use <br>
to separate them as like this
使用<br>
像这样将它们分开
var br = document.createElement("br");
element.appendChild(br);
回答by Abdul Munim
Rendering engines don't consider linefeedand carriage returnto be rendered. Better if you use a <br />
like this:
渲染引擎不考虑要渲染换行和回车。如果你使用<br />
这样的更好:
var textNode = document.createTextNode("Node on line 1");
element.appendChild(textNode);
var linebreak = document.createElement('br');
element.appendChild(linebreak);
var linebreak = document.createElement('br');
element.appendChild(linebreak);
textNode = document.createTextNode("Node on line 2");
element.appendChild(textNode);
Thanks Doug Owings. Also http://jsfiddle.net/Q8YuH/3/
回答by B.F.
To make it perfect.
使其完美。
function addText(node,text){
var t=text.split(/\s*<br ?\/?>\s*/i),
i;
if(t[0].length>0){
node.appendChild(document.createTextNode(t[0]));
}
for(i=1;i<t.length;i++){
node.appendChild(document.createElement('BR'));
if(t[i].length>0){
node.appendChild(document.createTextNode(t[i]));
}
}
}
addText(document,"Line 1 <br> Line 2<br/>line 3<BR/>");
回答by Marian Bazalik
var textNode = document.createTextNode("Node on line 1");
element.appendChild(textNode);
var linebreak = document.createElement('<br >');
element.appendChild(lineBreak);
textNode = document.createTextNode("Node on line 2");
element.appendChild(textNode);
回答by Jeff Wilbert
My guess is your trying to display them separate in an HTML view and not a TEXT view in which case you need to to insert <br />
tags between the text nodes via document.createElement('br')
to display them on separate lines. using \r
or \n
will only affect how it looks in source view.
我的猜测是您试图在 HTML 视图而不是文本视图中单独显示它们,在这种情况下,您需要<br />
在文本节点之间插入标签,document.createElement('br')
以将它们显示在单独的行上。使用\r
or\n
只会影响它在源视图中的外观。