admin管理员组

文章数量:1405340

After I grab an array of input element tags, I try to loop through them adding the onkeypress event listener to each one of them.

My Code:

window.onload = function()
{
    //  Add the event listeners to input tags
    //      Get the array of input tags
    var inputTags = document.getElementsByClassName('validateInput');
    console.log(inputTags);
    //      Loop through them, adding the onkeypress event listener to each one
    for (var i = 0; i < inputTags.lenght; i++)
    {
        var tag = inputTags[i];
        var functionToAdd = function(event, tag)
        {
            isNumberOrDot(event, tag);
        };
        tag.addEventListener('keypress', functionToAdd, false);
    }
};

Question:

Why isn't tag.addEventListener('keypress', functionToAdd, false); not adding the onkeypress event listener?

After I grab an array of input element tags, I try to loop through them adding the onkeypress event listener to each one of them.

My Code:

window.onload = function()
{
    //  Add the event listeners to input tags
    //      Get the array of input tags
    var inputTags = document.getElementsByClassName('validateInput');
    console.log(inputTags);
    //      Loop through them, adding the onkeypress event listener to each one
    for (var i = 0; i < inputTags.lenght; i++)
    {
        var tag = inputTags[i];
        var functionToAdd = function(event, tag)
        {
            isNumberOrDot(event, tag);
        };
        tag.addEventListener('keypress', functionToAdd, false);
    }
};

Question:

Why isn't tag.addEventListener('keypress', functionToAdd, false); not adding the onkeypress event listener?

Share Improve this question asked Jan 30, 2014 at 21:06 sargassargas 6,1808 gold badges54 silver badges70 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You have run into 3 issues in your code. First of all don't create functions inside loops, second is closure issue ( you will always get only last i value ) , third is that you have typo in length property, corrected code should be

window.onload = function()
{
    //  Add the event listeners to input tags
    //      Get the array of input tags
    var inputTags = document.getElementsByClassName('validateInput');
    console.log(inputTags);
    //      Loop through them, adding the onkeypress event listener to each one
    var functionToAdd = function(event, tag)
    {
        isNumberOrDot(event, tag);
    };
    for (var i = 0; i < inputTags.length; i++)
    {
        (function( i ) {
            inputTags[ i ].addEventListener('keypress', function( e ) {
                functionToAdd( e, inputTags[i] )    
            }, false);
        })( i );
    }
};

.length is spelled wrong above:

for (var i = 0; i < inputTags.length; i++) {}

本文标签: javascriptHow to add onkeypress event listener to input tagStack Overflow