在mozilla firefox中没有为javascript函数定义事件?

6 javascript firefox internet-explorer cross-browser

function onlyNumeric() {   
    if (event.keyCode < 48 || event.keyCode > 57) {
        event.returnValue = false; 
    }

}

onkeypress=onlyNumneric();
Run Code Online (Sandbox Code Playgroud)

在IE中,此代码工作正常.但是,在Mozilla Firefox中,该事件是一个未定义的错误.

tva*_*son 16

在FF/Mozilla中,事件作为参数传递给事件处理程序.使用类似下面的内容来解决IE中缺少的事件参数.

 function onlyNumeric(e)
 {
     if (!e) {
        e = window.event;
     }

     ...
 }
Run Code Online (Sandbox Code Playgroud)

你会发现两者之间还存在其他一些差异.此链接提供了有关如何以跨浏览器方式检测按下哪个键的一些信息.

  • 古老的问题..古老的解决方案......不知道什么时候我们将克服浏览器大战!;-) (2认同)