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

如何用jQuery或纯JS将表格行ID替换为数组对应值

Solution to Update tr IDs from Array

Yep, you're on the right track—you just need to first grab all the target <tr> elements, then pair each one with the corresponding value in your array. Here's how to do it with both pure JavaScript and jQuery:

Pure JavaScript Approach

First, select all <tr> elements with the whatever class, then iterate over them (alongside your array) to update each ID:

// Your existing array
var arr=['0','1','2','3','4'];

// Get all tr elements with class "whatever"
const trElements = document.querySelectorAll('tr.whatever');

// Loop through each tr and update its ID using the array's corresponding value
trElements.forEach((tr, index) => {
  tr.id = arr[index];
});

Alternatively, if you prefer to loop through the array directly (like your initial attempt), you can access the tr element by index:

arr.forEach((newId, index) => {
  trElements[index].id = newId;
});

jQuery Approach

If you're using jQuery, the each() method makes this straightforward—it gives you access to the index of each element, which you can use to pull the right value from your array:

var arr=['0','1','2','3','4'];

$('tr.whatever').each(function(index) {
  $(this).attr('id', arr[index]);
});

Or with an arrow function for more concise code:

$('tr.whatever').each((index, element) => {
  $(element).attr('id', arr[index]);
});

Both methods will keep your rows in their original order while replacing each tr's ID with the matching value from your array, resulting in exactly the structure you want.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:17:56