繁体   English   中英

在 JavaScript 中添加换行符或换行符无法按预期工作

[英]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 模式中?

*编辑 - 我做了更多的调查,但我仍然不知道为什么两个输出之一是正确的。

这是两个检查输出。 第一个显示未换行的行,但第二个正确地显示换行。 谁能看出这是为什么?

第一张包装不正确的图片

展开文本的手机视图

第二张图片显示了正确的包装,但 HTML 和 JS 除了 ID 之外是相同的。

而不是\\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.

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