更改为模板文字

时间:2019-07-02 13:29:33

标签: ecmascript-6

如何更改此代码:

var txt = "";
  txt += "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
  txt += "<p>Browser Name: " + navigator.appName + "</p>";
  txt += "<p>Browser Version: " + navigator.appVersion + "</p>";
  txt += "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
  txt += "<p>Browser Language: " + navigator.language + "</p>";
  txt += "<p>Browser Online: " + navigator.onLine + "</p>";
  txt += "<p>Platform: " + navigator.platform + "</p>";
  txt += "<p>User-agent header: " + navigator.userAgent + "</p>";

到模板文字? 我尝试过,但是做错了。 顺便说一下,这里的编辑器不允许我添加更多代码,否则我可以向您展示到目前为止我已经尝试过的内容。

1 个答案:

答案 0 :(得分:1)

喜欢这个:

var txt = `
  <p>Browser CodeName: ${navigator.appCodeName}</p>
  <p>Browser Name: ${navigator.appName}</p>
  <p>Browser Version: ${navigator.appVersion}</p>
  <p>Cookies Enabled: ${navigator.cookieEnabled}</p>
  <p>Browser Language: ${navigator.language}</p>
  <p>Browser Online: ${navigator.onLine}</p>
  <p>Platform: ${navigator.platform}</p>
  <p>User-agent header: ${navigator.userAgent}</p>
`;

看一下它是如何工作的: Template literals