capturing f5 keypress event in javascript using window.event.keyCode in [removed] event is always 0 and not 116

后端 未结 7 882
南方客
南方客 2020-11-29 09:02

i am creating an MVC application.There was a neccessitity to make a variable in a session to null upon closing of the application (i.e. window/tab) but not upon refreshing t

7条回答
  •  离开以前
    2020-11-29 09:16

    I agree with meo's solution, but I will add some modifications.

    when we use document.onkeydown = fkey; for example and in the page we have another method affected to the document.onkeydown then the browser will detect only the last event. However when we use : jQuery(document).on("keydown",fkey); even if we have another function to handle the keydown event, all the functions will be triggered.

    see the next example to more understand:

    var wasPressed = false;
    document.onkeydown = f1;
    document.onkeydown = f2;
    
    jQuery(document).on("keydown",f3); 
    jQuery(document).on("keydown",f4); 
    function f1(e){
    e = e || window.event;
    if( wasPressed ) return; 
    
            if (e.keyCode == 116) {
                 alert("f5 pressed");
                wasPressed = true;
            }else {
                alert("Window closed");
            }
    }
    function f2(){
        alert('f2');
    }
    function f3(){
        alert('f3');
    }
    function f4(){
        alert('f4');
    }
    

    what will be shown here: only 3 alerts: f2,f3 and f4. and the f1 function isn't triggred in this example.

提交回复
热议问题