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>

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

技术教程推荐

Go语言核心36讲 -〔郝林〕

深入剖析Kubernetes -〔张磊〕

数据结构与算法之美 -〔王争〕

玩转Git三剑客 -〔苏玲〕

从0开发一款iOS App -〔朱德权〕

编程高手必学的内存知识 -〔海纳〕

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

大厂广告产品心法 -〔郭谊〕

手把手带你写一个MiniSpring -〔郭屹〕

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