简体   繁体   English

如何在不使用document.write()的情况下在Javascript中开始新行?

[英]How do I start a new line in Javascript without using document.write()?

 var infoDiv = document.getElementById("info"); console.log(window); console.log(window.location); infoDiv.textContent += "The URL of this page is " + window.location.href; // i am hoping the following sentence can start in a new line infoDiv.textContent += "The user agent is " + window.navigator.userAgent; 

I tried document.write("\\n") as people suggested here , but Chrome gives me this violation warning: 我按照人们在这里建议的方式尝试了document.write("\\n") ,但是Chrome给了我这个违规警告:

[Violation] Avoid using document.write(). [违规]避免使用document.write()。 https://developers.google.com/web/updates/2016/08/removing-document-write https://developers.google.com/web/updates/2016/08/removing-document-write

What should I do? 我该怎么办? Thanks! 谢谢!

Line breaks in HTML are created with the <br> element (generally between text nodes). HTML中的换行符是使用<br>元素创建的(通常文本节点之间 )。 Paragraphs with the <p> element (generally around text nodes). <p>元素的段落(通常文本节点周围 )。

In either case you'll need to stop twiddling textContent because it will wipe out any elements you create. 在这两种情况下,您都需要停止搅动textContent因为它将清除您创建的所有元素。

Use document.createElement , document.createTextNode , and infoDiv.appendChild . 使用document.createElementdocument.createTextNodeinfoDiv.appendChild

You can append elements instead of text: 您可以附加元素而不是文本:

var infoDiv = document.getElementById("info");
infoDiv.append("The URL of this page is " + window.location.href);
// append new line
infoDiv.append(document.createElement('br'));
infoDiv.append("The user agent is " + window.navigator.userAgent);

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

相关问题 如何在不使用 document.write 的情况下在 JS 中打印新行? - How can I print a new line in JS without using document.write? JavaScript换行-document.write结尾 - Javascript new line - end of document.write javascript新手,如何更改-&gt; document.write(schedule [row] [&#39;title&#39;]))的颜色; 变成红色? - new to javascript, how do i change color of --> document.write(schedule[row]['title']); to red? 如何使用document.write()创建JavaScript来执行? - How do I get JavaScript created with document.write() to execute? 如何逐行读取HTML文件并使用Javascript为每一行返回document.write()? - How can I read line by line an HTML file and return document.write() for each line with Javascript? JavaScript:使用document.write(); - JavaScript: Using document.write(); 在不使用document.write的情况下将CSS样式应用于新窗口 - Apply CSS style to new window without using document.write 你如何用 document.write 写出 JavaScript 代码? - How do you write out JavaScript code with document.write? 如何在没有document.write的HTML页面中显示JavaScript变量 - How to display JavaScript variables in a HTML page without document.write 如何在不使用document.write的情况下将多个js文件加载到单个javascript文件中? - How to load the multiple js files in single javascript file, without using document.write?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM