简体   繁体   English

如何在此javascript命令中添加换行符

[英]how to add a line break to this javascript command

okay I have a script that outpouts an array like so 好吧,我有一个脚本,它的输出像这样

document.getElementById("message").innerHTML = msg;

the result I get is 我得到的结果是

line1 line2 line3 line4

I want it to be like this 我希望它像这样

line1
line2
line3
line4

I have tried adding the in various places but just cant get it to work 我尝试在各个地方添加,但是无法正常工作

my full code 我的完整代码

<html>
<head>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(a){
var msg="";
for(var i=0;i<a.length;i++){
msg+= a[i]+"\n";
}

document.getElementById("message").innerHTML = msg.join("</br>");

}
</script>
</head>
<title>
Welcome To ....
</title>
<body>
<center><h1> WELCOME TO .... </h1></center>
</br>
</br>
</br>
<center><form>
<textarea rows="7" cols="60" name="alpha"></textarea>
<br>
<input type="button"
value="show array"
onclick="showArray(textareaToArray(this.form.alpha ))">
</form></center>
</br>
<div id="message"></div>
</body>
</html>

You can use join() : 您可以使用join()

document.getElementById("message").innerHTML = msg.join('<br>');

jsfiddle 的jsfiddle

Edit according to OP's comment 根据OP的评论进行编辑

You don't need to loop through the array when using join: 使用join时,您无需遍历数组:

working jsfiddle 工作jsfiddle

function textareaToArray(text){
    return text.value.split(/[\n\r]+/);
}

function showArray(msg){
    document.getElementById("message").innerHTML = msg.join("<br/>");
}

Also you don't have specified a doctype... That's very important. 另外,您还没有指定doctype。这非常重要。 For HTML5 use <!DOCTYPE html> . 对于HTML5,请使用<!DOCTYPE html>

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

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