Passing parameters in Javascript onClick event

前端 未结 9 1056
滥情空心
滥情空心 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:25

    This is happening because they're all referencing the same i variable, which is changing every loop, and left as 10 at the end of the loop. You can resolve it using a closure like this:

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

    You can give it a try here

    Or, make this be the link you clicked in that handler, like this:

    link.onclick = function(j) { return function() { onClickLink.call(this, j); }; }(i);
    

    You can try that version here

提交回复
热议问题