Javascript页面重定向

Javascript页面重定向 首页 / JavaScript入门教程 / Javascript页面重定向

您可能会遇到以下情况:单击URL到达页面X,但在内部将您定向到另一个页面Y,这可以通过页面重定向实现。

在客户端使用JavaScript进行页面重定向非常简单,要将您的网站访问者重定向到新页面,只需增加 window.location 进行跳转。

<html>
   <head>
      <script type="text/javascript">
         <!--
            function Redirect() {
               window.location="https://www.learnfk.com";
            }
         //-->
      </script>
   </head>
   
   <body>
      <p>Click the following button, you will be redirected to home page.</p>
      
      <form>
         <input type="button" value="Redirect Me" onclick="Redirect();" />
      </form>
      
   </body>
</html>

您可以在将网站访问者重定向到新页面之前向其显示适当的消息,这将需要一点时间延迟才能加载新页面,以下示例显示了如何实现相同的函数。这里 setTimeout()是内置的JavaScript函数,可用于在给定的时间间隔后执行另一个函数。

<html>
   <head>
      <script type="text/javascript">
         <!--
            function Redirect() {
               window.location="https://www.learnfk.com";
            }            
            document.write("You will be redirected to main page in 10 sec.");
            setTimeout('Redirect()', 10000);
         //-->
      </script>
   </head>
   
   <body>
   </body>
</html>
You will be redirected to learnfk.com main page in 10 seconds!

以下示例显示了如何根据访问者的浏览器将网站访问者重定向到其他页面。

无涯教程网

<html>
   <head>     
      <script type="text/javascript">
         <!--
            var browsername=navigator.appName;
            if( browsername == "Netscape" ) {
               window.location="http://www.location.com/ns.htm";
            } else if ( browsername =="Microsoft Internet Explorer") {
               window.location="http://www.location.com/ie.htm";
            } else {
               window.location="http://www.location.com/other.htm";
            }
         //-->
      </script>      
   </head>
   
   <body>
   </body>
</html>

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

结构执行力 -〔李忠秋〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

朱涛 · Kotlin编程第一课 -〔朱涛〕

郭东白的架构课 -〔郭东白〕

OAuth 2.0实战课 -〔王新栋〕

DDD实战课 -〔欧创新〕

从0打造音视频直播系统 -〔李超〕

持续交付36讲 -〔王潇俊〕

深入浅出gRPC -〔李林锋〕

好记忆不如烂笔头。留下您的足迹吧 :)