简体   繁体   中英

javascript : window.location.href inside a “if”

I am a total newby in javascript and I am stuck with a problem.

Everything is happening within this "body" :

<body onKeyDown="myFunction(event);">

This code works : when I press escape on the page, there is a popup with 27. When I press another key, nothing happens. This is what I wanted.

Key_ESC = 27;
function myFunction(event) {
    if ( event.keyCode == 27 ){
        alert(event.keyCode);
    }
}

This code works : When I press any key, I go to next page. This is what I wanted.

Key_ESC = 27; 
function myFunction(event) {
        window.location.href=\"$INDEX/image`expr $compteur + 1`.html\";
}

But this one doesn't work : when I press any key nothing happens. I thought pressing escape would make a change of page (just like without the "if". It is not the case.

Key_ESC = 27;
function myFunction(event) {
    if ( event.keyCode == 27 ){
        window.location.href=\"$INDEX/image`expr $compteur + 1`.html\";
    }
}

Could any one explain to me why "window.location" doesn't work inside a "if" ? What did I do wrong ? I really have no idea at all....

Thank you very much.

You probably have to call event.preventDefault

also, in JS just do:

window.onload = function ()
{

Key_ESC=27;
Key_LEFT=37;

document
.   event = 
    {   preventDefault: function( e )
        {   e.preventDefault?e.preventDefault():e.returnValue=false;
        }
    }
;
document.body
.   onkeyup = function nextPage ( e )
    {   
        switch
        (   e.keyCode
        )   {   case Key_ESC
                :   document.event.preventDefault(e);
                    window.location.href=URL_NEXT;
                case Key_LEFT
                :   document.event.preventDefault(e);
                    window.location.href=URL_PREV;
            } 
    }

}

some time i can help

function myFunction(event) {
    if (event.keyCode == 27){
        window.location.href="<%= request.getContextPath()%>/INDEX/imagename.html";
    }
}

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