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

使用JavaScript从列表生成表格并控制进度条状态

解决JavaScript生成带进度条的表格问题

我来帮你搞定这个表格生成和进度条控制的问题!咱们一步步拆解需求,从基础结构到动态生成,再到进度条属性的修改方法。

1. 先准备基础HTML结构

首先,你用到了Bootstrap的进度条样式,所以要先引入Bootstrap的CSS(如果还没加的话),然后准备一个表格容器,让JS动态填充内容:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="container mt-4">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>T类值</th>
        <th>B类值</th>
        <th>进度</th>
      </tr>
    </thead>
    <tbody id="table-body">
      <!-- JS会在这里动态生成表格行 -->
    </tbody>
  </table>
</div>

2. 编写JavaScript生成表格逻辑

假设你的数据源是这样的二维数组(替换成你实际的数据即可):

const tableData = [
  ["T18", "T18_Beschreibung", 40],
  ["t0", "b0", 25],
  ["t1", "b1", 70],
  ["t2", "b2", 100]
];

接下来用JS循环遍历数据,动态创建每一行和进度条:

// 获取表格的tbody元素,作为行的容器
const tableBody = document.getElementById('table-body');

// 遍历每一组数据,生成表格行
tableData.forEach((item, index) => {
  // 解构出当前行的t、b、x值
  const [tValue, bValue, xValue] = item;

  // 创建表格行
  const row = document.createElement('tr');

  // 第一列:T类值(对应你示例中的th标签)
  const tCell = document.createElement('th');
  tCell.scope = 'row';
  tCell.id = `t_titel${index}`; // 给元素设置唯一ID,方便后续修改
  tCell.textContent = tValue;

  // 第二列:B类值
  const bCell = document.createElement('td');
  bCell.id = `t_des${index}`;
  bCell.textContent = bValue;

  // 第三列:进度条区域
  const progressCell = document.createElement('td');

  // 创建进度条外层容器
  const progressContainer = document.createElement('div');
  progressContainer.className = 'progress';

  // 创建进度条核心元素
  const progressBar = document.createElement('div');
  progressBar.id = `t_bar${index}`;
  progressBar.className = 'progress-bar progress-bar-striped bg-info';
  progressBar.setAttribute('role', 'progressbar');
  progressBar.setAttribute('aria-valuemin', '0');
  progressBar.setAttribute('aria-valuemax', '100');

  // 设置进度条的关键属性:宽度、aria-valuenow、显示文本
  progressBar.style.width = `${xValue}%`;
  progressBar.setAttribute('aria-valuenow', xValue);
  progressBar.textContent = `${xValue}%`;

  // 组装进度条到容器,再放到单元格里
  progressContainer.appendChild(progressBar);
  progressCell.appendChild(progressContainer);

  // 把所有单元格加到行里,再把行添加到tbody
  row.appendChild(tCell);
  row.appendChild(bCell);
  row.appendChild(progressCell);
  tableBody.appendChild(row);
});

3. 如何修改已生成的进度条属性

如果你后续需要修改某一行的进度条状态,比如把第0行的进度改成60%,可以这样做:

// 通过ID获取目标进度条
const targetBar = document.getElementById('t_bar0');

// 修改宽度
targetBar.style.width = '60%';
// 修改aria-valuenow属性
targetBar.setAttribute('aria-valuenow', 60);
// 修改显示文本
targetBar.textContent = '60%';

这里的关键是:

  • 修改元素的样式属性:直接用element.style.属性名(比如style.width)
  • 修改元素的HTML属性:用element.setAttribute('属性名', 值)(比如aria相关属性)

这样就能完全控制进度条的状态了,不用只局限于修改innerHTML。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:45:51