Passing parameters in Javascript onClick event

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

    This happens because the i propagates up the scope once the function is invoked. You can avoid this issue using a closure.

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

    Or if you want more concise syntax, I suggest you use Nick Craver's solution.

提交回复
热议问题