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?
2 Answers
Reset to default 3You 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++) {}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744895424a4599666.html
评论列表(0条)