使用for循环附加onclick方法 [英] Append onclick method using for loop

查看:94
本文介绍了使用for循环附加onclick方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将onclick事件附加到我正在动态创建的元素上.我正在使用下面的代码,这只是重要的部分.

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

现在发生的事情是,它总是将最后一个元素附加到所有onclick事件(又称元素)上.我在这里做错了什么?

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

推荐答案

这是一个经典问题.调用回调时,循环结束,因此i的值为content.length.

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

使用此示例:

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

此立即调用的函数为新变量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);
    };
  });
}

这篇关于使用for循环附加onclick方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆