模板文字不是插值变量

Template literals are not interpolating variables

今天才注意到带有 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);
}
<!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>

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

你需要改变这个:

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

对此:

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

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

请参阅以下工作示例:

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);
}
<!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>

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