Append onclick method using for loop

我是研究僧i 提交于 2019-12-02 15:53:06

问题


I'm appending onclick events to elements that I'm creating dynamically. I'm using the code below, this is the important part only.

Test.prototype.Show= function (contents) {
    for (i = 0; i <= contents.length - 1; i++) {
         var menulink = document.createElement('a');
         menulink.href = "javascript:;";
         menulink.onclick = function () { return that.ClickContent.apply(that, [contents[i]]); };
    }
}

First it says that it's undefined. Then I changed and added:

var content = content[i];
menulink.onclick = function () { return that.ClickContent.apply(that, [content]); };

What is happening now is that it always append the last element to all onclick events( aka elements). What I'm doing wrong here?


回答1:


It's a classical problem. When the callback is called, the loop is finished so the value of i is content.length.

Use this for example :

Test.prototype.Show= function (contents) {
    for (var i = 0; i < contents.length; i++) { // no need to have <= and -1
         (function(i){ // creates a new variable i
           var menulink = document.createElement('a');
           menulink.href = "javascript:;";
           menulink.onclick = function () { return that.ClickContent.apply(that, [contents[i]]); };
         })(i);
    }
}

This immediately called function creates a scope for a new variable i, whose value is thus protected.

Better still, separate the code making the handler into a function, both for clarity and to avoid creating and throwing away builder functions unnecessarily:

Test.prototype.Show = function (contents) {
    for (var i = 0; i <= contents.length - 1; i++) {
        var menulink = document.createElement('a');
        menulink.href = "javascript:;";
        menulink.onclick = makeHandler(i);
    }

    function makeHandler(index) {
        return function () {
            return that.ClickContent.apply(that, [contents[index]]);
        };
    }
};

A way to avoid this problem altogether, if you don't need compatibility with IE8, is to introduce a scope with forEach, instead of using a for loop:

Test.prototype.Show = function (contents) {
  contents.forEach(function(content) {
    var menulink = document.createElement('a');
    menulink.href = "javascript:;";
    menulink.onclick = function() {
      return that.ClickContent.call(that, content);
    };
  });
}


来源:https://stackoverflow.com/questions/20954005/append-onclick-method-using-for-loop

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