为什么在循环分配的最后索引元件的一个参考? [英] Why is the loop assigning a reference of the last index element to?

查看:99
本文介绍了为什么在循环分配的最后索引元件的一个参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个事件监听器添加到所有我的标签,日新月异的引用本身的作为一个参数,即使被触发时。下面是我写的函数:

I want to add an event listener to all of my tags, each passing a reference to itself as a parameter when the even is triggered. Here is the function I wrote:

function validateDigitsFeature()
{
    //  Add the event listeners to input tags
    //      Get the array of input tags
    var inputTags = document.getElementsByClassName('validateInput');
    var tagId;
    //      Loop through them, adding the onkeypress event listener to each one
    for (var i = 0; i < inputTags.length; i++)
    {
        //  Give each input element an id
        tagId = inputTags[i].id = 'input_id_' + i;
        inputTags[i].addEventListener('keyup', function(){isNumberOrDot(event, tagId);}, false);
    }
}

基本上函数应该做到以下几点:

Basically the function should do the following:


  1. 将所有输入数组中的变量与指定的类名

  2. 通过数组循环,增加一个ID为每个标签和

  3. 添加的onkeyup 事件监听器与 isNumberOrDot(事件,TAGID)处理程序。

  1. Store all the input tags with the specified classname in an array
  2. Loop through the array, adding an id to each tag and
  3. Adding the onkeyup event listener with the isNumberOrDot(event, tagId) handler.

添加的onkeyup事件,但他们每个人的处理程序是始终引用数组的最后一个元素的 TAGID

Problem

The onkeyup event is added, but they handlers of each one is always referencing the tagIdof the last element of the array.

什么是错的code /逻辑是什么?而且怎么能解决吗?

What is wrong with the code/logic? And how can it be fixed?

不确定这个问题是在循环有关的JavaScript封闭,而这个问题可以有一个更一般的答案,这是特定事件侦听器所使用。以更先进的开发者,它可能是很容易应用到这个问题的一般解决方案。但对我来说其他的解决方案仍然没有提供充分的解释,甚至合作。

Sure this problem is related to JavaScript Closure in loops, while this question could have a more general answer, it is specific to event listeners being used. To more advanced developers, it might be easy to apply the general solution to this problem. But to me the other solutions still didn't provide a full explanation or even worked.

感谢您提前。

推荐答案

由于实际事件的循环之后,在未来某个时候发生已经运行完毕,因此,其指数是在最后的价值,并在你的函数的局部变量如 TAGID 也是其最后的值。您需要建立某种形式的闭包$ P $的pserves值 I TAGID 唯一用于每个事件处理所以他们每个人都有获得自身的价值。

Because the actual event occurs sometime in the future after your for loop has already finished running and thus its index is at the last value and any local variables in your function like tagId are also at their last value. You need to create some sort of closure that preserves the value of i or tagId uniquely for each event handler so they each have access to their own value.

有几种不同的方式来做到这一点,但所有涉及路过 I 值函数为每个事件处理程序。

There are several different ways to do that, but all involve passing the i value to a function for each event handler.

这里有一个使用IIFE(立即调用函数前pression):

Here's one using an IIFE (immediately invoked function expression):

function validateDigitsFeature()
{
    //  Add the event listeners to input tags
    //      Get the array of input tags
    var inputTags = document.getElementsByClassName('validateInput');
    //      Loop through them, adding the onkeypress event listener to each one
    for (var i = 0; i < inputTags.length; i++)
    {
        //  Give each input element an id
        (function() {
            // creates a unique function context for each event handler so the
            // value of tagId is unique for each event handler
            var tagId = inputTags[i].id = 'input_id_' + i;
            inputTags[i].addEventListener('keyup', function(){isNumberOrDot(event, tagId);}, false);
        })();
    }
}

要做到这一点更常见的方式是从循环索引传递到关闭和做基于它在事件处理中的任何计算(尽管无论是法正常工作)是这样的:

A little more common way to do this is to pass the index from the for loop into the closure and do any calculation based on it inside the event handler (though either method works fine) like this:

function validateDigitsFeature()
{
    //  Add the event listeners to input tags
    //      Get the array of input tags
    var inputTags = document.getElementsByClassName('validateInput');
    //      Loop through them, adding the onkeypress event listener to each one
    for (var i = 0; i < inputTags.length; i++)
    {
        //  Give each input element an id
        (function(index) {
            // passes the `for` loop index into a function closure
            // so it is uniquely preserved for each event handler
            inputTags[index].addEventListener('keyup', function(){
                isNumberOrDot(event, inputTags[index].id = 'input_id_' + index);
            }, false);
        })(i);
    }
}

这篇关于为什么在循环分配的最后索引元件的一个参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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