最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

internet explorer - event is not defined in mozilla firefox for javascript function? - Stack Overflow

programmeradmin2浏览0评论
function onlyNumeric() {   
    if (event.keyCode < 48 || event.keyCode > 57) {
        event.returnValue = false; 
    }

}

onkeypress=onlyNumneric();

In IE, this code is working fine. However, in Mozilla Firefox, the event is an undefined error.

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

}

onkeypress=onlyNumneric();

In IE, this code is working fine. However, in Mozilla Firefox, the event is an undefined error.

Share Improve this question edited Sep 2, 2009 at 23:47 Ray 192k99 gold badges227 silver badges206 bronze badges asked Feb 16, 2009 at 13:06 pritipriti
Add a comment  | 

3 Answers 3

Reset to default 16

In FF/Mozilla the event is passed to your event handler as a parameter. Use something like the following to get around the missing event argument in IE.

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

     ...
 }

You'll find that there are some other differences between the two as well. This link has some information on how to detect which key is pressed in a cross-browser way.

Or quite simply, name the parameter event and it will work in all browsers. Here is a jQueryish example:

  $('#' + _aYearBindFlds[i]).on('keyup', function(event) {
  if(! ignoreKey({szKeyCodeList: gvk_kcToIgnore, nKeyCode: event.keyCode }))  this.value = this.value.replace(/\D/g, '');
  });

This example allows digits only to be entered for year fields (inside a for each loop selector) where ingoreKey() takes a keyCode list/array and compares the event keyCode and determines if it should be ignored before firing the bind event.

Keys I typically ingore for masks/other are arrow, backspace, tabs, depending on context/desired behaviour.

You can also typically use event.which instead of event.keyCode in most browsers, at least when you are using jQuery which depends on event.which to normalize the key and mouse events.

I don't know for sure what happens under the covers in the js engines, but it seems Mozilla FF respects a stricter scope, wherein, other browsers may be automatically addressing the window.event.keyCode scope on their own when the event is not explicitly passed in to a function or closure.

In FF, you can also address the event by window.event (as shown in some examples here) which would support this thought.

Some browsers may not support keyCode you have to use keyChar

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

}

onkeypress=onlyNumneric();
发布评论

评论列表(0)

  1. 暂无评论