Template literals are not interpolating variables

后端 未结 1 746
南旧
南旧 2020-12-22 12:52

Just noticed today that template literals with html tags don\'t work, or maybe I wrote it wrong?

I tried to include p tags in the template literals (which I commente

相关标签:
1条回答
  • 2020-12-22 13:14

    Templates are needed to be enclosed in backticks. You don't need to enclose template in quotes again.

    You need to change this:

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

    to this:

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

    The former is just a plain JavaScript string, but the latter is the template literal syntax and it allows the sections in ${ ... } to be interpolated.

    See the following working example:

    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>

    Read more about template literals in the documentation.

    0 讨论(0)
提交回复
热议问题