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

如何让jQuery代码正确迭代,为对应div设置匹配的CSS高度?

问题

需要将表格中id为out的行内各单元格数值,设置为id为graph的行内对应div的CSS高度(例如第一个单元格值50,第一个div高度设为50px)。当前代码使用.each方法,但所有div高度都被设为第一个单元格的50,无法实现对应迭代。

错误原因
  1. 每次遍历#out td时,用$("#out td").html()获取的始终是第一个td的内容,而非当前遍历到的td的值
  2. 内层循环$("div").each会把所有div的高度都覆盖成当前循环拿到的数值,最终所有div都会被重复设置为第一个td的值
修改方案

修改JS部分,利用.each的索引参数,将对应位置的td数值赋值给对应位置的div:

$(document).ready(function() {
  // 获取#graph里的所有div
  const graphDivs = $("#graph div");
  // 遍历#out的每个td
  $("#out td").each(function(index) {
    // 获取当前td的数值
    const num = parseInt($(this).html());
    // 找到对应索引的div,设置高度
    $(graphDivs[index]).css("height", num + "px");
  });
});

也可以反过来遍历div,通过索引匹配对应td:

$(document).ready(function() {
  const outTds = $("#out td");
  $("#graph div").each(function(index) {
    const num = parseInt($(outTds[index]).html());
    $(this).css("height", num + "px");
  });
});
完整代码示例
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table>
  <tr id="graph">
    <td>
      <div id="g1"></div>
    </td>
    <td>
      <div id="g2"></div>
    </td>
    <td>
      <div id="g3"></div>
    </td>
  </tr>
  <tr id="out">
    <td>50</td>
    <td>60</td>
    <td>70</td>
  </tr>
</table>
table {
  border: 1px solid #000;
  border-collapse: collapse;
}

#g1 {
  background-color: blue;
  border: 1px solid #000;
}

#g2 {
  background-color: red;
  border: 1px solid #000;
}

#g3 {
  background-color: green;
  border: 1px solid #000;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:25:01