开发者

javascript: how to check a property is undefined

开发者 https://www.devze.com 2023-01-21 12:08 出处:网络
I have codes below. elem.onkeypress=function(e){ if( (e.which===undefined?e.keyCode:e开发者_高级运维.which)==13 ){

I have codes below.

elem.onkeypress=function(e){
 if( (e.which===undefined?e.keyCode:e开发者_高级运维.which)==13 ){
   //dosomething
  }
}

at IE8, it occus erros: 'which' is null or not an object

how to fix this problem.


The problem is that e is undefined in IE because no event object is passed as a parameter to the event handler. You need the window.event property:

elem.onkeypress=function(e) {
  e = e || window.event;
  var charCode = e.which || e.keyCode;
  if (charCode == 13) {
    //dosomething
  }
};


One option is to go with (e.hasOwnProperty('which') ? ...


use typeof:

if (typeof e.which == 'undefined' ? e.keyCode : e.which) == 13)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号