我有一堆 HTML 数字输入,我已经通过以下方式获取了它们
x=document.querySelectorAll('input[type="number"]');
然后,我尝试使用 for 循环对其进行迭代,并应用 onkeyup
函数。功能是这样的:
t=function(elem){
elem.onkeyup=function(e) {
if(!/[\d\.]/.test(String.fromCharCode(e.which))) {
elem.value='';
}
};
};
基本上,它的作用是清除输入的值(如果输入了字母)。我知道我可以通过 HTML 应用它:
<input type='number' onkeyup='t(this)'/>
但是我怎样才能用Javascript做到这一点呢?我尝试用以下方法迭代它:
x=document.querySelectorAll('input[type="number"]');
for(i=0; i<x.length; i++){
x[i].onkeyup=t(this);
}
但它不起作用。我究竟做错了什么?我怎样才能做到这一点?请仅使用常规 JavaScript 答案,不要使用 jQuery 或其他框架/库。
最佳答案
改变
x[i].onkeyup=t(this);
至
x[i].onkeyup=t(x[i]);
因为这
不是你想要的
关于JavaScript 无法将现有函数应用于 onkeyup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32447009/