Why does setting [removed].href not stop script execution

后端 未结 3 592
别跟我提以往
别跟我提以往 2021-01-11 18:33

The following code changes the location to www.bing.com regardless of wether redirect is 1 or any other number. If redirect is 1, it logs \"is redirecting\" and then redirec

3条回答
  •  北海茫月
    2021-01-11 19:14

    That's because everything after the if is executed as well, but it looks like there's a difference between Chrome and FF (haven't tested in IE).

    Example code:

    var redirect = 1;
    
    if (redirect == 1) {
        console.log("is redirecting");
        document.location.assign('https://developer.mozilla.org/');
    }
    
    alert('go');
    document.location.assign('https://www.bing.com/');
    

    In Chrome 'go' is alerted, and you're redirected to bing.com. In Firefox, 'go' is alerted, but you're redirected to MDN.

    I think, the best thing to do is to wrap the other stuff in an else.

提交回复
热议问题