[英]Adding a line break or line-wrap in JavaScript not working as anticipated
我正在使用这一行:
userResultMapOne = "But your value of " + userInputMapOne + " \nis too high for this scenario."
我尝试了多种使用 \\n 来换行的不同方法。 实际上,我真正想要的是让文本在移动设备上自动换行到下一行,但出于某种奇怪的原因,文本只是离开了屏幕(它以 Bootstrap 模式显示)。
允许 JS innerHTML DOM 修改包装在小型设备上的正确方法是什么,尤其是在 Bootstrap 模式中?
*编辑 - 我做了更多的调查,但我仍然不知道为什么两个输出之一是正确的。
这是两个检查输出。 第一个显示未换行的行,但第二个正确地显示换行。 谁能看出这是为什么?
而不是\\n替换<br>
您可能正在使用innerHTML
来插入您的字符串,您应该使用innerText
const userInputMapOn = '[USER_VALUE]'; const userResultMapOne = "But your value of "+ userInputMapOn + "\\nis too high for this scenario"; const p1 = document.querySelector('#innerHTML'); const p2 = document.querySelector('#innerText'); p1.innerHTML = '_ With innerHTML : ' + userResultMapOne; p2.innerText = '_ With innerText : ' + userResultMapOne;
<p id="innerHTML"></p> <p id="innerText"></p>
使用模板文字:
const userInputMapOn = '[USER_VALUE]'; const userResultMapOne = `But your value of ${userInputMapOn} \\nis too high for this scenario`; const p = document.querySelector('p'); p.innerText = userResultMapOne;
<p></p>
编辑 :
如果您需要将 HTML 与字符串一起插入,只需将\\n
替换为<br>
并像这样使用innerHTML
:
const userInputMapOn = '[USER_VALUE]'; const userResultMapOne = `But your value of <b>${userInputMapOn}</b> \\nis too high for this scenario`; const p = document.querySelector('p'); p.innerHTML = userResultMapOne.replace(/(?:\\r\\n|\\r|\\n)/g, '<br>');
<p></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.