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

如何用CSS为JS循环中document.write的输出设置样式?

问题解决:document.write加HTML标签报错+实现网格布局样式

一、为什么会出现SyntaxError: 意外的'<'?

你遇到的报错大概率是字符串拼接时的引号冲突。比如如果你的代码写成这样:

document.write("<div class="bike-card">"+ motorbikeList[i].name +"</div>");

外层用双引号包裹整个字符串,里面的class="bike-card"又用了双引号,会导致浏览器把第一个"当成字符串结束标记,后面的<div...就变成未被引号包裹的无效语法,自然触发报错。

你的示例代码里的<br>能正常运行,是因为用了单引号包裹,和外层的双引号不冲突,但如果要添加带属性的复杂HTML标签,就很容易踩这个坑。

二、正确的写法:用ES6模板字符串

用反引号(`)包裹的模板字符串是最省心的方案,支持换行、直接插入变量,还能彻底避免引号冲突:

let motorbikeList = [ 
  { name: "Ducati V4r", horsepower: 240 },
  { name: "Ducati V4", horsepower: 214 },
  { name: "Ducati V2", horsepower: 155 },
  { name: "Yamaha R1", horsepower: 197 },
  { name: "Yamaha R6", horsepower: 133 }
];

// 先获取页面上的容器(需要提前在HTML中添加这个元素)
const gridContainer = document.getElementById('motorbike-grid');

for (let i = 0; i < motorbikeList.length; i++) {
  const bike = motorbikeList[i];
  // 用模板字符串编写完整的HTML结构
  let bikeHtml = `
    <div class="bike-card">
      <h3>${bike.name}</h3>
      <p>HP: ${bike.horsepower}</p>
      ${bike.horsepower >= 220 ? '<p class="high-power">Wow! That\'s a lot of horsepower!</p>' : ''}
    </div>
  `;
  // 将HTML插入容器,替代document.write
  gridContainer.insertAdjacentHTML('beforeend', bikeHtml);
}

三、实现网格布局的CSS配置

先在HTML中添加一个容器元素:

<div id="motorbike-grid"></div>

然后编写CSS实现网格布局:

#motorbike-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px;
}

.bike-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.high-power {
  color: #e74c3c;
  font-weight: bold;
}

四、为什么不推荐用document.write?

document.write在页面加载完成后调用会清空整个页面,而且不利于维护复杂的HTML结构。用容器+insertAdjacentHTML的方式,更灵活也符合现代JS开发的规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:10:53