动态添加id到每个表格单元格 [英] add id dynamically to each table cells
问题描述
我正在尝试创建一个动态的js表,我想动态地给每个单元格的id。我想使用这些ids来使用不同的js事件处理程序。怎么办?我尝试过不同的方式,但没有一个工作!
I am trying to create a dynamic js table and I want to give id to each cell dynamically. I want to use those ids to use in different js event handlers. How it can be done? I have tried in different ways but none of them works!
<html>
<head>
<style>
#colors{
float:right;
width:400px;
height:400px;
}
</style>
</head>
<body>
<script>
var d;
var k=0;
function makeit(){
var tbl=document.createElement("table");
var atts=document.createAttribute("style");
atts.value="border:1px solid black;text-align:center;padding:2px;margin:3px 3px 3px 3px;";
tbl.setAttributeNode(atts);
for(i=0;i<5;i++){
var rows=tbl.insertRow(i);
for(j=0;j<7;j++){
d=rows.insertCell(j);
d.height="50px";
d.width="50px";
d.style.backgroundColor="yellow";
d.addEventListener("click",function myfunc(){d.style.backgroundColor="red";});
}
}
document.body.appendChild(tbl);
}
window.onload=makeit;
</script>
</body>
</html>
推荐答案
只需添加
d.id = "r" + i + "c" + j;
d=rows.insertCell(j);
在每个 td
上设置唯一的ID。
显然,您可以根据自己的喜好更改语法 r2c4
(这将是3.行和5.单元格)。
to set unique ids on each td
.
Obviously, you can change the syntax r2c4
(which would be 3. row and the 5. cell) to your own liking.
如果要在点击特定的 td
时调用函数,您甚至可以传递行索引( i
)和列索引( j
)。
If you want to call a function when clicking on a specific td
you could even pass the row index (i
) and column index (j
) to that function.
旁注
您应该考虑使用JavaScript库或框架,如 jQuery 这样的操作。这将有助于您长期的工作。
Side note
You should consider using a JavaScript library or framework like jQuery for manipulations like this. It would facilitate your work a lot in the long term.
这篇关于动态添加id到每个表格单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!