javascript 将 id 动态添加到每个表格单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23003341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:10:41  来源:igfitidea点击:

Add id dynamically to each table cells

javascriptdynamichtml-table

提问by AL-zami

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!

我正在尝试创建一个动态 js 表,并且我想动态地为每个单元格提供 id。我想将这些 id 用于不同的 js 事件处理程序。怎么做?我尝试了不同的方法,但没有一个有效!

<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>

回答by Horen

Just add

只需添加

d.id = "r" + i + "c" + j;

under

在下面

d=rows.insertCell(j);

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.
显然,您可以根据r2c4自己的喜好更改语法(即 3.row 和 5.cell)。

If you want to call a function when clicking on a specific tdyou could even pass the row index (i) and column index (j) to that function.

如果您想在单击特定函数时调用函数,td您甚至可以将行索引 ( i) 和列索引 ( j) 传递给该函数。

Side note
You should consider using a JavaScript library or framework like jQueryfor manipulations like this. It would facilitate your work a lot in the long term.

旁注
您应该考虑使用 JavaScript 库或框架(如jQuery)进行此类操作。从长远来看,这将极大地促进您的工作。

回答by wongcode

The problem is a scope issue. When adding the event listener, d's reference gets updated to be the last table cell you have created.

问题是范围问题。添加事件侦听器时,d的引用将更新为您创建的最后一个表格单元格。

You can simply change the event listener's function to:

您可以简单地将事件侦听器的功能更改为:

function myfunc() {
     this.style.backgroundColor="red";
}

So that thisreferences the object it is attached to. Depending on your intention, you may not need unique ids if you have access to the cell itself.

这样就this引用了它所附加的对象。根据您的意图,如果您有权访问单元本身,则可能不需要唯一的 ID。

回答by enhzflep

Using an approach that includes wongcode's solution, you may wish to consider the following code:

使用包含 wongcode 解决方案的方法,您可能希望考虑以下代码:

<html>
<head>
<style>
#myTbl{ border:1px solid black;text-align:center;padding:2px;margin:3px 3px 3px 3px; }
#myTbl td{ width: 50px; height: 50px; background-color: yellow;}
</style>
</head>
<body>
<script>

function onCellClicked(e)
{
    this.style.backgroundColor = 'red';
}

function makeit()
{
    var tbl=document.createElement("table");
    tbl.id = 'myTbl';
    var curCellIndex = 0;
    for(i=0;i<5;i++)
    {
        var rows=tbl.insertRow(i);
        for(j=0;j<7;j++)
        {
            d=rows.insertCell(j);
            d.id = 'cell_' + curCellIndex;
            curCellIndex++;
            d.addEventListener("click",onCellClicked, false);
        }
     }
    document.body.appendChild(tbl);
}

window.onload=makeit;
</script>
</body>
</html>

Some of the advantages include:

其中一些优点包括:

  • Smaller html file created in your editor
  • Smaller html code created in the browser
  • Use of context and the this keyword
  • Smaller memory consumption, since each TD doesn't contain the full body of the event handler (it only include a 'pointer' to the function to be executed)
  • 在编辑器中创建的较小的 html 文件
  • 在浏览器中创建的较小的 html 代码
  • 使用上下文和 this 关键字
  • 更少的内存消耗,因为每个 TD 不包含事件处理程序的完整主体(它只包含一个指向要执行的函数的“指针”)

EDIT: forgot to add code to give the cells an id. Now fixed.

编辑:忘记添加代码来给单元格一个 id。现在固定了。