如何用简洁数学函数按行给HTML表格的tr元素编号?
需求:为表格tr元素按视觉行位置生成编号
我有一个包含27个tr元素的嵌套表格,这些tr按三列分组排列。需要按表格从上到下的视觉行位置给tr编号:
- 第1、4、7个tr属于视觉第一行,编号为1
- 第2、5、8个tr属于视觉第二行,编号为2
- ...
- 第21、24、27个tr属于视觉第九行,编号为9
我已有几种手动JS实现方法,现寻求简洁的数学函数来完成该需求。
数学公式实现
情况1:tr序号从1开始(按文档顺序计数第n个tr)
行编号公式:
Math.floor((n - 1) / 9) * 3 + ((n - 1) % 3) + 1
情况2:tr索引从0开始(比如JS中NodeList的索引)
行编号公式:
Math.floor(index / 9) * 3 + (index % 3) + 1
JS示例代码
// 获取目标tr元素(带data-column属性的tr) const targetTrs = document.querySelectorAll('tr[data-column]'); // 遍历并为每个tr添加行编号属性 targetTrs.forEach((tr, idx) => { const rowNum = Math.floor(idx / 9) * 3 + (idx % 3) + 1; tr.setAttribute('data-row', rowNum); // 控制台打印验证 console.log(`第${idx + 1}个tr的行编号:${rowNum}`); });
原始HTML代码
<table dir="auto" style=" height: 400; width: 400; border-color: azure; border-width: 3; "> <tbody> <tr> <th> <table> <tbody data-general-square="1"> <tr data-column="1">1</tr> <tr data-column="2">2</tr> <tr data-column="3">3</tr> </tbody> </table> </th> <th> <table> <tbody data-general-square="2"> <tr data-column="4">4</tr> <tr data-column="5">5</tr> <tr data-column="6">6</tr> </tbody> </table> </th> <th> <table> <tbody data-general-square="3"> <tr data-column="7">7</tr> <tr data-column="8">8</tr> <tr data-column="9">9</tr> </tbody> </table> </th> </tr> <tr> <th> <table> <tbody data-general-square="4"> <tr data-column="10">10</tr> <tr data-column="11">11</tr> <tr data-column="12">12</tr> </tbody> </table> </th> <th> <table> <tbody data-general-square="5"> <tr data-column="13">13</tr> <tr data-column="14">14</tr> <tr data-column="15">15</tr> </tbody> </table> </th> <th> <table> <tbody data-general-square="6"> <tr data-column="16">16</tr> <tr data-column="17">17</tr> <tr data-column="18">18</tr> </tbody> </table> </th> </tr> <tr> <th> <table> <tbody data-general-square="7"> <tr data-column="19">19</tr> <tr data-column="20">20</tr> <tr data-column="21">21</tr> </tbody> </table> </th> <th> <table> <tbody data-general-square="8"> <tr data-column="22">22</tr> <tr data-column="23">23</tr> <tr data-column="24">24</tr> </tbody> </table> </th> <th> <table> <tbody data-general-square="9"> <tr data-column="25">25</tr> <tr data-column="26">26</tr> <tr data-column="27">27</tr> </tbody> </table> </th> </tr> </tbody> </table>
内容的提问来源于stack exchange,提问作者shalomOlam
相关产品推荐
相关产品推荐

