如何使用JavaScript在HTML文本中添加新行

How to add a new line to HTML text using JavaScript?

本文关键字:添加 新行 文本 HTML 何使用 JavaScript      更新时间:2023-09-26

我使用的代码基本上是在屏幕上键入文本。我不确定如何在正在显示的字符串中添加新行。

我已经尝试了'n那些张贴他们的答案。这行不通。在我的HTML

中没有开始新行代码:

var myString = "public class MyResume implements Resume{" +
    /*this is where I want the new line*/ "...." ;
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
  if(myArray.length > 0) {
    document.getElementById("myTypingText").innerHTML += myArray.shift();
  } else {
    clearTimeout(loopTimer); 
    return false;
  }
  loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
<div id="myTypingText"></div>

您也可以像使用"your string.<br> new line"一样使用<br>

这是一个使用完整代码的过于简单的方法。使用波浪线~,然后在frameLooper中插入一个
,如下所示:

<html>
<body>
<div id="myTypingText"></div>
<script>
var myString = 'public class MyResume implements Resume{~....' ;
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
    var char = myArray.shift();
        if (char === '~')
    { document.getElementById("myTypingText").innerHTML += '<br/>'; }
    else
    { document.getElementById("myTypingText").innerHTML += char; }
} else {
    clearTimeout(loopTimer); 
            return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
</body>
</html>

简单地将<br>添加到myString不工作,因为您一次插入每个字符。当使用innerHTML添加字符时,JavaScript将其编码为:

$('element').innerHTML += "<";
> "string&lt;" 

如果你对<br>中的每个字符都这样做,你最终会得到

>"string&lt;br&lt;"

你需要一些方法告诉你的脚本添加整个元素,当你到达一个"中断字符"。您可以使用一个不常见的字符,如管道|,或者您可以添加一个方法,以确保后面的几个字符不会拼写为<br>

要将字符串添加到新行,您需要字符串中的'n。例如:

var string = 'This is the first line 'nThis is the second line'
console.log(string)

这将输出

This is the first line 
This is the second line

为什么不直接在文本后面加上ul>li或p呢,就像这样:

document.getElementById("myTypingText").innerHTML += "<p>" + myArray.shift() "</p>";

document.getElementById("myTypingText").innerHTML += "<li>" + myArray.shift() "</li>";

:

<ul id="myTypingText"></ul>