简体   繁体   中英

An issue with javascript syntax comprehension

Could someone please explain to me this statement in Javascript :

var keyCode = window.event ? window.event.keyCode : e.which;

Any help greatly appreciated !

This is the ternary conditional operator .

Here it is used to get the window.event.keyCode value if window.event exists, e.which in other cases.

Some browsers don't recognise window.event . This is called ternary operator. It's a way to be sure the code works in different browsers and a short way to write:

If window.event is not undefined then keyCode = window.event.keyCode , otherwise keycode = e.which

var Keycode = window.event? window.event.keyCode : e.which


var Keycode;
if(window.event)
Keycode = window.event.keyCode;
else
Keycode  = e.which;

It means

var keyCode;
if(window.event){
  keyCode = window.event.keyCode;
} else {
  keyCode = e.which;
}

You should see Javascript grammar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM