简体   繁体   English

循环上的addEventListener不适用于IIFE

[英]addEventListener on loop not working with IIFE

In the code below, the value of j is always set to the last of the iteration. 在下面的代码中, j的值始终设置为迭代的最后一个。 I'm already using an IIFE, but it still gives the non-expected behavior. 我已经在使用IIFE,但是它仍然给出了意外的行为。 Is there something that I'm doing wrong? 我做错什么了吗?

function renderUsers(users) {
    const frag = document.createDocumentFragment();
    const userList = document.getElementById('user-list');

    // Create and append all the users on the user list
    for (var j = 0; j < users.length; j++) {
        var item = document.createElement('li');
        var division = document.createElement('div');
        var userName = document.createElement('span');
        var deleteButtonAnchor = document.createElement('a');
        var deleteButton = document.createElement('i');
        deleteButton.classList.add('material-icons');
        deleteButton.textContent = 'delete_forever';
        (function() {
            deleteButton.addEventListener('click',function() {
                console.log(j);
            });
        })();
        deleteButtonAnchor.appendChild(deleteButton);
        division.appendChild(userName);
        division.appendChild(deleteButtonAnchor);
        item.appendChild(division);


        userName.appendChild(document.createTextNode(users[j].name.first+' '+users[j].name.last));
        frag.appendChild(item);
    }
    userList.appendChild(frag);
}

What you want to do with closure, is to pass the iterating variable as a parameter, as such: 您要对闭包进行的操作是将迭代变量作为参数传递,如下所示:

 (function(j) {
     deleteButton.addEventListener('click',function() {
          console.log(j); // j is the parameter
     });
 })(j);

Or as @torazaburo fairly noticed in the comments, you can use let keyword for a iterating variable to eliminate the need to create closures. 或者,正如@torazaburo在注释中相当注意的那样,您可以对迭代变量使用let关键字来消除创建闭包的需要。 More on the let keyword you can find here . 更多关于let关键字,您可以在这里找到。 Note however, that it is ES6 feature, which is not implemented in older browsers, so you may need to transpile it first (for example using babel). 但是请注意,它是ES6功能,在较旧的浏览器中未实现,因此您可能需要先进行编译(例如,使用babel)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM