You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Template literals无法插值变量、嵌入HTML标签失效,求解决方案

Hey Wei, let's tackle those template literal issues you're running into—they're super common once you start working with dynamic content, so let's break them down one by one!

1. Fixing Variable Interpolation in Template Literals

First up: if your variables aren't being interpolated into the template literal, the most likely culprit is one of two things:

  • You're using single quotes (') or double quotes (") instead of backticks (`) to wrap the template literal. Template literals rely on backticks to recognize the ${variable} syntax.
  • The variable you're trying to interpolate isn't in the current scope (e.g., it's defined outside the callback function where you're using the template literal).

For example, this won't work:

// ❌ Wrong quotes, interpolation won't happen
const wrongText = 'My favorite animal is ${animalName}';

But this will:

// ✅ Correct backticks, variable gets interpolated
const animalName = "Red Panda";
const rightText = `My favorite animal is ${animalName}`;

Double-check that in your code, every template literal is wrapped in backticks, and the variables you're trying to use are accessible where you're writing the template.

2. Getting Embedded HTML Tags to Render

The second issue—HTML tags not working in your template literal—almost always boils down to how you're inserting the template into the DOM. If you're using textContent to set the content of your aniBox element, the browser will treat the HTML tags as plain text instead of rendering them.

Instead, you need to use innerHTML to tell the browser to parse and render the HTML.

Here's how to adjust your code to make that work, using your animal data 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() {
    if (ourRequest.status >= 200 && ourRequest.status < 400) {
      var animalData = JSON.parse(ourRequest.responseText);
      let htmlContent = '';
      
      // Loop through the data and build HTML with template literals
      animalData.forEach(animal => {
        // Now your <p> tags will be rendered properly!
        htmlContent += `
          <div class="animal-entry">
            <h2>${animal.name}</h2>
            <p>Species: ${animal.species}</p>
            <p>Age: ${animal.age}</p>
            <p>Favorite foods: ${animal.foods.likes.join(', ')}</p>
          </div>
        `;
      });
      
      // Use innerHTML to inject the rendered HTML
      aniBox.innerHTML = htmlContent;
    } else {
      aniBox.innerHTML = '<p>Oops, failed to load animal data.</p>';
    }
  };
  
  ourRequest.onerror = function() {
    aniBox.innerHTML = '<p>Error connecting to the server.</p>';
  };
  
  ourRequest.send();
});

Quick Troubleshooting Tips

  • If you had the <p> tag commented out before, uncomment it and make sure it's inside the backtick-wrapped template literal.
  • Double-check that you're not accidentally escaping the HTML tags (e.g., using \ before < or >—that would turn them into text).
  • If you're still seeing plain text instead of rendered HTML, inspect the element in your browser's dev tools to see if the tags are being added as text nodes (which means you used textContent) or as actual elements (which means you did it right!).

Hope these fixes get your template literals working smoothly! Let me know if you run into any other snags.

内容的提问来源于stack exchange,提问作者Wei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:45:48