模板文字不是插值变量

时间:2018-04-11 14:26:54

标签: javascript ecmascript-6 template-literals

今天刚才注意到带有html标签的模板文字不起作用,或者我写错了?

我尝试在模板文字中加入p标签(我在代码段中注释掉了),但它没有用。有没有人有任何想法?谢谢!



var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');

blueBtn.addEventListener('click', function() {
    var ourRequest = new XMLHttpRequest();
    ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
    ourRequest.onload = function() {
        var ourData = JSON.parse(ourRequest.responseText);
        addHTML(ourData)
    };
    ourRequest.send();
});

function addHTML(data) {
    var content = '';
    for (let i of data) {
        console.log(i);
        content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
 //content += '`<p>${i.name} is a ${i.species}.</p>`'; <--this one doesn't work
    }
    aniBox.insertAdjacentHTML('beforeend', content);
}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JSON and AJAX</title>
</head>
<body>
    <header>
        <h1>JSON and AJAX</h1>
        <button id="btn">Fetch Info for 3 New Animals</button>
    </header>

    <div id="animal-info"></div>

    <script src="js/main.js"></script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

模板需要用反引号括起来。您不需要再次将模板括在引号中。

你需要改变这个:

'`<p>${i.name} is a ${i.species}.</p>`'

到此:

`<p>${i.name} is a ${i.species}.</p>`

前者只是一个普通的JavaScript字符串,但后者是模板文字语法,它允许插入${ ... }中的部分。

请参阅以下工作示例:

&#13;
&#13;
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');

blueBtn.addEventListener('click', function() {
  var ourRequest = new XMLHttpRequest();
  ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
  ourRequest.onload = function() {
    var ourData = JSON.parse(ourRequest.responseText);
    addHTML(ourData)
  };
  ourRequest.send();
});

function addHTML(data) {
  var content = '';
  for (let i of data) {
    console.log(i);
    // content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
    content += `<p>${i.name} is a ${i.species}.</p>`;
  }
  aniBox.insertAdjacentHTML('beforeend', content);
}
&#13;
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>JSON and AJAX</title>
</head>

<body>
  <header>
    <h1>JSON and AJAX</h1>
    <button id="btn">Fetch Info for 3 New Animals</button>
  </header>

  <div id="animal-info"></div>

  <script src="js/main.js"></script>
</body>

</html>
&#13;
&#13;
&#13;

在文档中阅读有关template literals的更多信息。