简体   繁体   English

将文档元素的innerHTML设置为长字符串

[英]Set document element's innerHTML to a long string

I'm using JQuery to dynamically set a div element. 我正在使用JQuery动态设置div元素。 It has multiple lines that have very specific spacing, so this is my code: 它有多行具有非常特定的间距,所以这是我的代码:

document.getElementById('body').innerHTML = "Developer:  A <br/> &emsp;&emsp; &emsp; &emsp; &nbsp;&nbsp; B <br> &emsp; &emsp; &emsp; &emsp; &nbsp; C <br> &emsp; &emsp; &emsp; &emsp;&nbsp;&nbsp; D";

As you can see this code looks horrible, is there any way to set the innerHTML line by line? 如您所见,此代码看起来很可怕,是否有任何方法可以逐行设置innerHTML? For example, 例如,

document.getElementById('body').innerHTML = "Developer:  A";     
document.getElementById('body').innerHTML = "Developer:  B"; 

and have it show up the same way? 并以相同的方式显示吗?

Thank you! 谢谢!

You want the text in separate lines inside the body, use div to get the text in the separate lines as below. 您希望文本在正文中以单独的行显示,请使用div如下所示在单独的行中获取文本。

 $(function() { $("<div/>").html("Developer A").appendTo($("body")); $("<div/>").html("Developer B").appendTo($("body")); $("<div/>").html("Developer C").appendTo($("body")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> </body> 

Yes. 是。 If you want to add string you can use += 如果要添加字符串,可以使用+=

document.getElementById('body').innerHTML = "Developer:  A";     
document.getElementById('body').innerHTML += "Developer:  B"; 

You can span multiple lines: 您可以跨越多行:

 document.getElementById('body').innerHTML = "Developer: A <br/>" + "Developer: B"; 

Or, you can do multiple assignments: 或者,您可以执行多个任务:

 document.getElementById('body').innerHTML = "Developer: A <br/>"; document.getElementById('body').innerHTML += "Developer: B"; // Note the += instead of just = 

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

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