如何为数组中每个元素生成独立<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
相关产品推荐
相关产品推荐

