Passing values to onclick [duplicate]

混江龙づ霸主 提交于 2019-12-17 06:14:17

问题


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.


回答1:


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



回答2:


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);
}



回答3:


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



来源:https://stackoverflow.com/questions/1582634/passing-values-to-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!