简体   繁体   English

使用javascript使用数组填充表格

[英]Populate a table with an array using javascript

I have an html table and I have an array in JavaScript. 我有一个html表,并且有一个JavaScript数组。 I'm able to populate the table correctly. 我能够正确填充表格。 The only issue is, I'm adding divs inside the td with an onclick event. 唯一的问题是,我要在td中添加一个带有onclick事件的div。

var workout = wo["workout"];

for(i=0;i<workout.length;i++){
    for(j=0;j<workout[i].length;j++){
        for(k=0;k<workout[i][j].length;k++){

            var td = document.getElementById(i+"-"+j);

            var closediv = document.createElement("div");
            closediv.className = "closediv";
            closediv.innerHTML = "x";

            closediv.onclick = function () {
                console.log(workout[i][j][k].id);
            };

            var exdiv = document.createElement("div");
            exdiv.id = workout[i][j][k].id;
            exdiv.className = workout[i][j][k].extype;
            exdiv.innerHTML = workout[i][j][k].exercise;
            exdiv.appendChild(closediv);

            td.appendChild(exdiv);
        }
    }
}

The id works correctly here: 该ID在这里正常工作:

exdiv.id = workout[i][j][k].id;

The id doesn't work when I have it here: 我在这里找到ID时不起作用:

closediv.onclick = function () {
                console.log(workout[i][j][k].id);
            };

Please let me know what I've done wrong 请让我知道我做错了什么

SOLUTION

Try this code instead: 请尝试以下代码:

closediv.onclick = function () {
   console.log(this.parentNode.id);
});

DEMO DEMO

See this jsFiddle for demonstration. 请参阅此jsFiddle进行演示。

I think its closure loop issue. 我认为它的闭环问题。

if you want to get proper value one of the work around can be : 如果您想获得适当的价值,解决方法之一可以是:

 closediv.onclick = function () {
     (function(i, j, k) {
         console.log(workout[i][j][k].id);
      )(i, j, k);
 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM