JavaScript反码多行字符串在IE中不起作用 [英] JavaScript Backtick Multiline String not working in IE
问题描述
我有一个包含在 var
中的大HTML字符串。我使用它来写入 innerHTML
。
I have a large HTML string contained in a var
. I'm using it to write to innerHTML
.
第一个示例(带反引号语法),它是最简单的,在IE11中不起作用。
The first example (with backtick syntax), which is the simplest, does not work in IE11.
有没有办法让第一个例子在IE11中工作,而不必使用数组或换行符?
Is there a way to get the first example to work in IE11 without having to use an array or newline characters?
Backtick`
https://jsfiddle.net/qLm02vks/
<div id="display"></div>
var message = `
<p>this</p>
<p>is</p>
<p>a</p>
<p>multiline</p>
<p>string</p>
`;
// Write Message
var display = document.getElementById('display');
display.innerHTML = message;
适用于IE
数组加入
Works in IE
Array Join
https://jsfiddle.net/3aytojjf/
var message =
['<p>this</p>',
'<p>is</p>',
'<p>a</p>',
'<p>multiline</p>',
'<p>string</p>'
].join('\n');
适用于IE
with linebreak \
Works in IE
Single Quote ' with linebreak \
https://jsfiddle.net/5qzLL4j5 /
var message =
'<p>this</p> \
<p>is</p> \
<p>a</p> \
<p>multiline</p> \
<p>string</p>'
;
推荐答案
问题
字符串的反引号语法是 >模板文字 ,它允许插入字符串和多行字符串中的变量。他们不支持IE11(详情请参阅: ES6 compat表) p>
解决方案
Problem
The backtick syntax for a string is a Template Literal, which allows for interpolation of variables within a string and multiline strings. They are not supported by IE11 (see more here: ES6 compat table).
- 您可以使用一个转换器,例如流行的
巴别塔。这会将模板文字
转换为IE11可以理解的ES5语法。 - 您可以选择不支持支持IE11的
,并坚持支持Edge和其他浏览器
,这些支持支持原生ES6,尽管这通常不是一种选择。
- You can use a transpiler, such as the ever-popular Babel. This will convert the template literal into the ES5 syntax that IE11 understands.
- You could opt-out of supporting IE11, and stick with support for Edge and other browsers that have native ES6 support, though this is usually not an option.
这篇关于JavaScript反码多行字符串在IE中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!