我在 html 中创建了表格单元格,其 id 以 1 递增,例如:cell1、cell2、cell3、......、cell100。
我想做的是遍历并使用 for 循环获取对这些单元格中每一个的引用,因为一个一个地引用它们不是很好的做法,并且需要大量的行代码,而不是这个;
var cell1 = document.getElementById('cell1');
var cell2 = document.getElementById('cell2');
var cell3 = document.getElementById('cell3');
......
var cell100 = document.getElementById('cell100');
有没有可能做这样的事情?
for (i = 0; i<=100; i++) {
var cell+i = document.getElementById("cell"+i);
// then I can call individual cells and assign tasks to them something along the lines of;
cell1.addEventListener('input',function(){}
cell5.background = '#f5f5f5'
cell55.innerHTML = 'I am cell 55'
etc..
}
编辑:
Incase 它可能有用,我有 1 个表,其中包含许多单元格,其中一些有 ID,有些没有。我只想引用那些确实有 ID 的。
最佳答案
您可以使用带有通配符的document.querySelectorAll
var slice = Array.prorotype.slice;
var selection = document.querySelectorAll("[id^=cell]");
slice.call(selection).forEach(function(item, index){
// here item is the table row and index is the iteration number of forEach
// to get the id
var id = item.id;
//to get the numerical value in id
var number_in_id = item.id.match(/\d+/g)[0];
})
document.querySelectorAll("[id^=cell]")
选择其 id 以字符串 cell
开头的所有元素,如果你想让它特定于表td 你添加 document.querySelectorAll("td[id^=cell]")
关于javascript - 在 Javascript 中循环遍历表格单元格 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35432649/