Yemto
Yemto

Reputation: 613

Javascript add onclick event in a loop

How do I add onclick events to elements in a loop? I have tried it like this.

            var c = "#FFFFFF"
            for(var i=0; i<_data.length; i++){
                c = c == "#FFFFFF" ? "#D8D8D8" : "#FFFFFF";

                var row = table.insertRow(rowCount++);
                row.style.backgroundColor = c;
                row.onclick = function(){
                    clickEvent(_data[i][0]);
                }

                newColl(row,i,0,_data[i][1]); //Name
                newColl(row,i,1,_data[i][2]); //Surname
                newColl(row,i,2,_data[i][3]); //Time working

                newColl(row,i,3,""); //TO-DO: Started at
                newColl(row,i,4,""); //TO-DO: Walked home
                newColl(row,i,5,""); //TO-DO: Took lunch
            }

I know that don't work, and I know why. But I don't know how to fix it.

Upvotes: 0

Views: 1220

Answers (1)

shanks
shanks

Reputation: 922

DO NOT DO THAT!!!!!. This is the exact reason why Event Delegation exists. Just attach ONE click event to the parent of the elements you are looping through and they should automatically dispatch click events when clicked.

click here for an explanation

Upvotes: 1

Related Questions