在获取一组输入元素标签后,我尝试循环遍历它们,并为每个标签添加 onkeypress 事件监听器。
我的代码:
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);
}
};
问题:
为什么 tag.addEventListener('keypress', functionToAdd, false);
不添加 onkeypress 事件监听器?
最佳答案
您的代码中遇到了 3 个问题。首先,不要在循环内创建函数,其次是闭包问题(你总是只能得到最后一个 i
值),第三是你在 length
属性中有拼写错误,更正后的代码应该是
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 );
}
};
关于javascript - 如何将 onkeypress 事件监听器添加到输入标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21467391/