Analysis of Invalid window. location. href redirection settings in JS
Problem
Window. location. href redirection setting in JS is invalid.
The Code is as follows:
<script type="text/javascript"> function checkUser(){ if(2!=1){ window.location.href="login.jsp"; }} </script>
The reason is that the href jump of tag a will be executed before the jump set by window. location. href:
If the form is used, the form is submitted first.
After submission, the current page is no longer displayed. Therefore, window. location. href is invalid.
Solution 1
Add
Window. event. returnValue = false
This attribute is placed in The onclick event in the submission form. In this click event, the form is not submitted. If it is placed in a hyperlink, The href attribute of the hyperlink is not executed in this click event.
After the code is changed to the following code, window. location. href is successfully redirected:
<script type="text/javascript"> function checkUser(){ if(2!=1){ window.location.href="login.jsp"; window.event.returnValue=false; }} </script>
Solution 2
In the click event, onclick = "checkUser ()" becomes onclick = "return checkUser ();"
And return false in checkUser; in this case, the href of the a tag will not be executed. In this way, the window. location. href can be smoothly redirected.
The Code is as follows:
<script type="text/javascript"> function checkUser(){ if(<%=flag%>!=1){ window.location.href="login.jsp"; return false; }} </script>