Template literals are not interpolating variables

后端 未结 1 748
南旧
南旧 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条回答
  •  萌比男神i
    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:

    '`

    ${i.name} is a ${i.species}.

    `'

    to this:

    `

    ${i.name} is a ${i.species}.

    `

    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 += '

    ' + i.name + ' is a ' + i.species + '.

    '; content += `

    ${i.name} is a ${i.species}.

    `; } aniBox.insertAdjacentHTML('beforeend', content); }
    
    
    
    
      
      
      
      JSON and AJAX
    
    
    
      

    JSON and AJAX

    Read more about template literals in the documentation.

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