简体   繁体   English

Javascript 新线内置字符串?

[英]Javascript new line built string?

I'm building a string in JavaScript FE like you can see below, my attempt is to print some data in different rows.我正在 JavaScript FE 中构建一个字符串,如下所示,我的尝试是在不同的行中打印一些数据。 In my JavaScript I build the string the use getElement() and textContent to attach the string at the paragraph.在我的 JavaScript 中,我使用getElement()textContent构建字符串以在段落中附加字符串。

I've tried <br> <br/> \n <\r , all with no results.我试过<br> <br/> \n <\r ,都没有结果。

var str;
str+="text" + data[0];
  str+= //Here need new line
str+="text" + data[1];

var p=document.getElementById("paragraph");
p.textContent = str;

A couple options you have are:您有几个选择:

  1. put a <br/> in the string and set the p.innerHTML = str instead of setting textContent在字符串中放置一个<br/>并设置p.innerHTML = str而不是设置 textContent

 let myEl = document.getElementById('myelement'); let data = 'test 1'; data += '<br/>'; data += 'test 2'; myEl.innerHTML = data;
 <div id="myelement"></div>

OR或者

  1. put a \n character in the string and then use a white-space: pre in the CSS of your element在字符串中放置一个\n字符,然后在元素的 CSS 中使用white-space: pre

 let myEl = document.getElementById('myelement'); let data = 'test 1'; data += '\n'; data += 'test 2'; myEl.textContent = data;
 #myelement { white-space: pre; }
 <div id="myelement"></div>

It might be easier to use a template string , and then use innerText rather than textContent as they are different .使用模板字符串可能更容易,然后使用innerText而不是textContent ,因为它们是不同的

 const arr = ['Bob', 'Jane']; const str = ` text: ${arr[0]} text: ${arr[1]} `; document.body.innerText = str;

If you need a string that can be displayed/downloaded as a file and displayed in html at the same time, i would use \n and innerText :如果您需要一个可以作为文件显示/下载并同时显示在 html 中的字符串,我会使用\ninnerText

var str;
str+="text" + data[0];
  str+= '\n';
str+="text" + data[1];

var p=document.getElementById("paragraph");
p.innerText = str;


the \n will be replaced by <br/> automatically when using innerText, and you wont need to style it with whitespace , and you could use the resulting string, to perhaps start a file download在使用 innerText 时, \n将被自动替换为<br/> ,您不需要使用whitespace来设置它的样式,并且您可以使用生成的字符串,也许可以开始文件下载

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

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