我说,当我使用反引号警报消息不正确显示:如何在使用反引号时正确显示JavaScript警报内的文本?
例子:
var classicMsg = "Lorem Ipsum is simply dummy text of the printing and typesetting "
\t \t \t + "ndustry. Lorem Ipsum has been the industry's standard dummy "
\t \t \t + "text ever since the 1500s, when an unknown printer took a galley "
\t \t \t + "of type and scrambled it to make a type specimen book.";
var backticksMsg = `Lorem Ipsum is simply dummy text of the printing and typesetting
ndustry. Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.`;
document.getElementById("btnAlert1").addEventListener('click', function(){
alert(classicMsg);
});
document.getElementById("btnAlert2").addEventListener('click', function(){
\t alert(backticksMsg);
});
li{cursor: pointer;}
<ul>
<li id="btnAlert1">Test with classic message</li>
<li id="btnAlert2">Test with backticks message</li>
</ul>
是否有更好的方法来正确显示警报反引号文字比写一个自定义函数来做到这一点?...我的意思是没有做这样的事情:
function formatTextBeforeCallingAlert(txt) {
return txt.replace(/\n/g, '').replace(/\t/g, '');
}
“插入源的任何新行字符是模板文字的一部分”。 - [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) - 所以除非你想换行,否则不要添加换行符。 – Gerrit0
@ gerrit0但我不想失去使用“插值”插入变量内容的优势... –
为什么删除新行会阻止插值? – charlietfl