如何在不使用 CSS 的情况下在动态添加的 javascript DOM 元素中保留空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10474696/
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 preserve whitespace in dynamically added javascript DOM element without using CSS?
提问by Travis J
When adding in text with small whitespace appended to it for alignment purposes the whitespace is trimmed off (the whitespace is added in c# so by the time it gets to front end Javascript it cannot be edited - it would be nice to just use some CSS to do this but it is not an option).
当添加带有小空格的文本以进行对齐时,空格会被修剪掉(空格是在 c# 中添加的,所以当它到达前端 Javascript 时,它无法被编辑 -只使用一些 CSS 会很好这样做,但它不是一个选项)。
Here is what I tried so far:
这是我到目前为止尝试过的:
<div id="testDiv"></div>
<script type="text/javascript">
var zlp = document.getElementById("testDiv");
zlp.innerHTML = "hello hello";
var zzz = document.createTextNode("hello hello");
zlp.appendChild(zzz);
</script>
Both of which produce hello hello
.
两者都产生hello hello
.
回答by Felix Kling
White space characters are usually collapsed in HTML (by default).
You can replace it with the
entity:
您可以将其替换为
实体:
var text = text.replace(/\s/g, ' ');
\s
will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g
instead.
\s
将匹配任何空白字符,例如空格、制表符和换行符。如果您只想替换空间,请/ /g
改用。
Other options which avoid string manipulation:
避免字符串操作的其他选项:
- Put the text in a
pre
element. - Set the CSS 2
white-space
property topre
as @Esailijapointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.
回答by gotofritz
White space is collapsed in HTML. It's not a JS issue, the same would happen if you typed that manually in the HTML document. You need to replace the spaces with
空白在 HTML 中折叠。这不是 JS 问题,如果您在 HTML 文档中手动输入,也会发生同样的情况。您需要用 替换空格
zlp.innerHTML = "hello hello".replace( / /g, " " );
回答by PitaJ
use
利用
zlp.innerHTML = "hello hello";
Like everyone else just said.
就像其他人刚刚说的那样。
回答by Wagner Pereira
use a html tag 'pre'
使用 html 标签“pre”
Example:
例子:
<pre>
A line
A line with indent
</pre>
result:
结果:
A line A line with indent