0

i create an table with createElement. The table, tr and td get an id. Every td gets an dblclick eventlistener. So when you do an dblick a div will be shown.

but i get back the wrong id. I get only the id of the last entry.

I check the entry in the debugg mode,it's ok, why i get only the last id?

i want to get the id of the element, when i do a dblclick.

Insert Function:

countTable ++;

document.getElementById("counterTable").value = countTable;
var range= sel.getRangeAt(0);

myParent=document.getElementById("iframe_editor").contentWindow.document.body;
table=document.createElement("TABLE");

table.id = "tableid"+countTable;

for (i = 1; i <= document.getElementById("numoftr").value; i++)
{
    tr = document.createElement("TR");
    tr.id = table.id+"-"+"trid"+i;

    for (j = 1; j<= document.getElementById("numoftd").value; j++)
    {
        td = document.createElement("TD");
        td.id = tr.id+"-"+"tdid"+j;

        td.addEventListener( 'dblclick', function(){
            loadTableAttribute(td.id);
        },td.id);

        tr.appendChild(td);             
    }
    table.appendChild(tr);
}
table.appendChild(emptyNode);

myParent.appendChild(table);
range.insertNode(table);

LoadTableAttribute

function loadTableAttribute(tdid)
{
    alert(tdid);
}
maxhb
  • 8,554
  • 9
  • 29
  • 53
Stefan Gum
  • 67
  • 5
  • 3
    Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – CBroe Jan 26 '16 at 18:44
  • From within the for-loop call an outside function and attach your event there. Not within the for-loop. Second is the last argument of the `attachEventListener` just `true/false` and refers to the bubble phase. Standard is "false". – Daniel Jan 26 '16 at 18:54

1 Answers1

0

Use var tr = .. and var td = .. and in the listener send this.id to the function: loadTableAttribute(this.id);

EDIT A good post about var usage is this. Always use var in relevant scopes.

Community
  • 1
  • 1
guysigner
  • 2,822
  • 1
  • 19
  • 23