如何用jQuery或纯JS将表格行ID替换为数组对应值
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

