Passing parameters in Javascript onClick event

前端 未结 9 1028
滥情空心
滥情空心 2020-12-02 09:43

I\'m trying to pass a parameter in the onclick event. Below is a sample code:

9条回答
  •  情歌与酒
    2020-12-02 10:38

    link.onclick = function() { onClickLink(i+''); };
    

    Is a closure and stores a reference to the variable i, not the value that i holds when the function is created. One solution would be to wrap the contents of the for loop in a function do this:

    for (var i = 0; i < 10; i++) (function(i) {
        var link = document.createElement('a');
        link.setAttribute('href', '#');
        link.innerHTML = i + '';
        link.onclick=  function() { onClickLink(i+'');};
        div.appendChild(link);
        div.appendChild(document.createElement('BR'));
    }(i));
    

提交回复
热议问题