简体   繁体   中英

Can Anybody Please Explain The Below Statement

<script>
    function AvoidSpace(event) {
        var k = event ? event.which : window.event.keyCode;
        if (k >= 42 && k <= 57 || k == 32 || k == 61 || k == 13) return false;
    }

    function ExceptNumber(event) {
        var k = event ? event.which : window.event.keyCode;
        if (k >= 0 && k <= 47 || k >= 58 && k <= 122) return false;
    }

    function NumChar(event) {
        var k = event ? event.which : window.event.keyCode;
        if (k >= 0 && k <= 31 || k >= 33 && k <= 64 || k >= 91 && k <= 96) return false;
    }

    function clearFunction() {
        document.getElementById('register').reset();
    }
</script>

My doubt is: var k = event ? event.which : window.event.keyCode;

I was confused with the above statement. One thing is for sure that the above statement is for event validation only..I'm not getting the explanation..Can anyone please help me in finding out what actually the above statement does?? Seeking for a brief explanation in JAVASCRIPT only

k = event ? event.which : window.event.keyCode

Means if you passed event variable to function use it; Else - use global event if you passed event variable to function use it; Else - use global event

It's ternary operator and can be expanded to

if (event == true) {
    k = event.which;
} else {
    k = window.event.keyCode;
}

It will return which key was pressed (integer value; key code)

This syntax:

expression ? value1 : value2;

Is known as a ternary operator. If the expression is true, it will return value1 otherwise return value2. In this case an object (event) is used as the expression, so it will evaluate if it exists (not null) or not.

Some browsers use keyCode, others use which. That instruction is only for cross browser issue, and is used to retrive the key code during keypress and keyup events

event ? event.which : window.event.keyCode;

This is a ternary operator. If the thing before the question mark is true or "truthy," it returns the expression before the colon; if it is false or "falsey," it returns the expression after.

If event is defined (ie, it was passed into the function) it will be "truthy," which means that it is true if evaluated as a boolean even though it isn't of a boolean type.

So what this does is check if event was passed into the function, and set k either to event.which (the key code that caused the event) if it was passed in, or to the the keycode from the global window event as a fallback otherwise.

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