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?
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++) {}
本文标签: javascriptHow to add onkeypress event listener to input tagStack Overflow
版权声明:本文标题:javascript - How to add onkeypress event listener to input tag - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744895423a2631034.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论