简体   繁体   English

如何在元素的文本中动态添加空格?

[英]How to dynamically add whitespace in element's text?

I want to insert whitespace in DOM element. 我想在DOM元素中插入空格。

For instance, I want to change this 例如,我想改变这一点

<a></a>

to this 对此

<a> </a>

If I manually add &nbsp to DOM element, then it renders &nbsp as a whitespace. 如果我手动添加&nbsp到DOM元素,那么它呈现&nbsp作为空白。 But when I want to add this dynamically, I use innerText , 但是当我想动态添加它时,我使用innerText

 a_element.innertText = "&nbsp"

and as result it doesn't convert &nbsp to whitespace and renders it as a text ( <a>&nbsp</a> ). 并且因此它不会转换&nbsp空白字符和呈现为一个文本( <a>&nbsp</a> )。 How can I fix this? 我怎样才能解决这个问题?

根据需要使用.innerHTML编辑该特定链接的HTML。

a_element.innerHTML = "&nbsp;"

HTML entity references are processed only in HTML parsing. HTML实体引用仅在HTML解析中处理。 In any case, it is best to put the character directly into the content. 无论如何,最好将角色直接放入内容中。 If you do not know how to type the no-break space in your authoring environment, you can use the \\xA0 or escape in JavaScript: 如果您不知道如何在创作环境中\\xA0空格,则可以在JavaScript中使用\\xA0转义:

a_element.innerText = "\u00A0";

BTW, the no-break space is not a whitespace character by HTML specs. 顺便说一句, 不间断空格不是HTML规范的空白字符

You can also just copy the whitespace character you want and paste it into your javascript string. 您也可以只复制所需的空白字符并将其粘贴到您的javascript字符串中。 For instance, I had a &emsp; 例如,我有一个&emsp; in my html; 在我的HTML; when I loaded the page, I copied that space and pasted it into a string in my javascript: 当我加载页面时,我复制了该空格并将其粘贴到我的javascript中的字符串中:

var myString = "Here is &emsp; --> <--";

Note that it looks like a regular space on here, but it renders into the original whitespace copied. 请注意,它在此处看起来像一个常规空间,但它会渲染到复制的原始空格中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM