如何在不使用 innerHTML 的情况下在 JavaScript 中添加不间断的空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19810122/
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 do I add a non-breaking whitespace in JavaScript without using innerHTML?
提问by frequent
I'm generating content dynamically and in some instances, I need to set a
as the only content of a <span>
element.
我正在动态生成内容,在某些情况下,我需要将 a 设置
为<span>
元素的唯一内容。
However, the following adds
as text vs adding a empty space:
但是,以下添加
为文本与添加空白区域:
var foo = document.createElement("span")
foo = document.createTextNode(" ");
which makes sense, so I'm wondering, how would I add
correctly without (!) using innerHTML
这是有道理的,所以我想知道,如果
没有 (!) 使用,我将如何正确添加innerHTML
Thanks for help!
感谢帮助!
回答by vcsjones
You can use a unicode literal for a non breaking space:
您可以使用 unicode 文字作为不间断空格:
var foo = document.createTextNode("\u00A0");
回答by CodeFanatic
If you don't want to use innerHTML
, you can use a hexadecimal escape.
如果不想使用innerHTML
,可以使用十六进制转义。
The most common:
最普遍的:
\x20
– standard space or\s
\xC2\xA0
– non-breaking space or
\x0D
– carriage return or\r
\x0A
– newline or\n
\x09
– tab or\t
\x20
– 标准空间或\s
\xC2\xA0
– 不间断空间或
\x0D
– 回车或\r
\x0A
– 换行或\n
\x09
– 标签或\t
In your case: \xC2\xA0
在你的情况下: \xC2\xA0