Analysis of Invalid window. location. href redirection settings in JS

Source: Internet
Author: User

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>                     
 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.