我正在尝试使它成为所以我没有为每个输入字段都写一个函数,我想使用它。而是将元素ID发送给函数,并且只有一个函数可以回收。Javascript-将函数变量的元素id分配给事件监听器
工作原理是这样
<input name="field" id="field" type="text" onKeyPress="onlyNum()" />
<script type="text/javascript">
function onlyNum() {
var name = $("#field");
name.keypress(function (e) {
if (e.which > 0 && // check that key code exists
e.which != 8 && // allow backspace
!(e.which >= 48 && e.which <= 57) // allow 0-9
) {
e.preventDefault();
}
});
}
</script>
但它不喜欢这个工作,但是这就是我要为:
<input name="field" id="field" type="text" onKeyPress="onlyNum('field')" />
<script type="text/javascript">
function onlyNum(theInput) {
var name = document.getElementById(theInput);
name.keypress(function (e) {
if (e.which > 0 && // check that key code exists
e.which != 8 && // allow backspace
!(e.which >= 48 && e.which <= 57) // allow 0-9
) {
e.preventDefault();
}
});
}
</script>
因此,没有人知道什么是错的第二个例子?我怎样才能让它工作。谢谢
尝试更改为'onKeyPress =“onlyNum(this)”'然后'this.keypress(function(e){...})'。你在使用jQuery吗? – 2012-08-11 09:07:10
如果您使用的是jQuery,那么上面的代码非常低效且不必要。 – 2012-08-11 09:08:54