Passing values to onclick [duplicate]

If I create a whole lot of HTML elements using a loop, like

for (i= 1; i < 100; i++) {
    var my_element = document.createElement ("td");
    row.appendChild (my_element);
    my_element.onclick = function () {my_function (i));
}

then when the element is clicked, the value of i passed to my_function is always 100, regardless of what number element is calling it. I have worked around this by using

my_element.id = "something"+i;
my_element.onclick = function (e) {my_function (e.target.id)};

(For Internet Explorer, the target needs to be srcElement, apparently.) I am curious to know whether there is any way to create the function without having to add the ID to the element like this.

Answers:

Answer

The value of i changes with each iteration of the loop. You need a closure to capture the value of i:

(function(i) {
    my_element.onclick = function () {my_function (i)};
}(i))
Answer

If you write a function which builds you a handler function, you can use the new scope which that gives you to ensure that you get the number you want. For example:

function BuildHandler (i) { return function () { alert(i); };

for (i= 1; i < 100; i++) {
    var my_element = document.createElement ("td");
    row.appendChild (my_element);
    my_element.onclick = BuildHandler(i);
}
Answer

if I were you I will use Jquery (or prototype or whatever js frameworks that available)

on each elements you should add attributes like myid for example so that when you did on click you can retrive it.

for(i=1; i ++ ; i<100){
   var myelement = "<td myid='something"+i+"' class='myTD'></td>" ;
   row.append(myelement);
}

.... 

$(document).ready(function(){
  $('.myTD').click(function(){
     var id = $(this).attr('myid');
     my_function(id);
  });

});

I did this trick on my web app :)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.