javascript将\ n替换为< br>在createTextNode里面 [英] javascript Replacing \n with <br> inside createTextNode
本文介绍了javascript将\ n替换为< br>在createTextNode里面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带 \ n
的字符串-Java脚本中的换行符,我想使用Javascript中的 createTextNode()
替换另一个文本.
I have a String with \n
- line breaks in Javascript, that I want to replace for another text using createTextNode()
in Javascript.
<script type="text/javascript">
function changeText() {
var Explanation="Test\n Test2";
var parent3 = document.getElementById("The_Explanation");
parent3.innerHTML='';
var myP3 = document.createElement("p");
var myText3 = document.createTextNode(""+Explanation);
myP3.appendChild(myText3);
parent3.appendChild(myP3);
}
</script>
到目前为止,所有尝试将换行符插入新文本都失败了.将 \ n
替换为< br>
的所有函数只会把我带到结果
All tries to get the line break into the new text failed so far. All functions that replace \n
to <br>
only bring me to the result
"Test<br> Test2"
有任何想法吗?
推荐答案
您不能将元素节点放在文本节点内.文本节点不能有子节点.
You can't put an element node inside a text node. Text nodes cannot have child nodes.
- 将字符串拆分为新行
- 遍历数组并为每个部分生成一个文本节点
- 使用
createElement('br')
创建一个换行符,以在每个文本节点之间移动 - 附加以上所有内容
- Split your string on new lines
- Loop over the array and generate a text node for each part
- Use
createElement('br')
to create a line break to go between each text node - append all of the above
这篇关于javascript将\ n替换为< br>在createTextNode里面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文