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

如何为数组中每个元素生成独立<li>标签?前端代码求助

问题解决:将颜色数组转为独立
  • 标签
  • 假设你的things.json结构如下:

    {
      "colors": ["红色", "蓝色", "绿色"]
    }
    

    现有错误代码示例(将所有颜色塞进单个
  • ):
  • fetch('things.json')
      .then(res => res.json())
      .then(data => {
        const list = document.getElementById('color-list');
        const singleLi = document.createElement('li');
        singleLi.textContent = data.colors.join(' ');
        list.appendChild(singleLi);
      });
    

    修改方案1:遍历数组逐个创建
  • (安全可靠,推荐)
  • 通过forEach遍历颜色数组,为每个颜色单独创建<li>元素并添加到列表中:

    fetch('things.json')
      .then(res => res.json())
      .then(data => {
        const list = document.getElementById('color-list');
        data.colors.forEach(color => {
          const li = document.createElement('li');
          li.textContent = color; // 自动转义特殊字符,避免XSS风险
          list.appendChild(li);
        });
      });
    

    修改方案2:生成HTML字符串批量插入(适合简单场景)

    用map将每个颜色转为<li>字符串,拼接后一次性插入列表:

    fetch('things.json')
      .then(res => res.json())
      .then(data => {
        const list = document.getElementById('color-list');
        // 拼接所有<li>字符串
        const listHtml = data.colors.map(color => `<li>${color}</li>`).join('');
        list.innerHTML = listHtml;
        // 注意:如果颜色值包含HTML特殊字符(如<、>),优先用方案1避免XSS风险
      });
    

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

    相关产品推荐
    方舟 Agent Plan

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

    最近更新时间:2026.08.22 03:45:53