使用jQuery或纯 JavaScript 如何将用户从一页转到另一页?


当前回答

原始问题:“如何使用 jQuery 重新定向?” , 因此, 答案执行 jQuery 补充使用案例 。


重定向到 JavaScript 的页面 :

window.location.href = "/contact/";

或者,如果您需要延迟:

setTimeout(function () {
  window.location.href = "/contact/";
}, 2000);   // Time in milliseconds

jjQuery 允许您从网页中轻松选择元素。 您可以在页面中找到任何您想要的内容, 然后使用 jQuery 添加特殊效果, 对用户动作作出反应, 或者在您选中的元素内或外显示内容并隐藏内容。 所有这些任务都以知情开始如何选择元素或事件.

$('a,img').on('click',function(e){
  e.preventDefault();
  $(this).animate({
    opacity: 0 //Put some CSS animation here
  }, 500);
  setTimeout(function(){
    // OK, finished jQuery staff, let's go redirect
    window.location.href = "/contact/";
  },500);
});

想象一下有人写了一个脚本/ 插件, 包含 10000 行代码 。 如果有 jQuery , 您可以用一两行代码连接到这个代码 。

其他回答

警告: 警告:答案只是作为一种可能的解决办法而已;显然最好的解决方案,因为它需要jQuery。 相反,它更喜欢纯 JavaScript 解决方案。

$(location).prop('href', 'http://stackoverflow.com')

在 JavaScript 和 jQuery 中, 我们使用以下代码重定向页面 :

window.location.href="http://google.com";
window.location.replace("page1.html");

但您可以在 jQuery 中设定函数, 以重定向页面 :

jQuery.fn.redirect=function(url)
{
    window.location.href=url;
}

调用此函数 :

jQuery(window).redirect("http://stackoverflow.com/")

但如果有人想重回主页 他可能会使用下面的片段

window.location = window.location.host

如果你有三种不同的环境,如发展、中转和生产,将会很有帮助。

您可以将这些单词放入铬控制台, 来探索此窗口或窗口。 位置对象 。 @ info: whatsthis火虫控制台

从客户的侧面调整方向:

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript and jQuery example to redirect a page or URL </title>
    </head>
    <body>
        <div id="redirect">
            <h2>Redirecting to another page</h2>
        </div>

        <script src="scripts/jquery-1.6.2.min.js"></script>
        <script>
            // JavaScript code to redirect a URL
            window.location.replace("http://stackoverflow.com");
            // window.location.replace('http://code.shouttoday.com');

            // Another way to redirect page using JavaScript

            // window.location.assign('http://code.shouttoday.com');
            // window.location.href = 'http://code.shouttoday.com';
            // document.location.href = '/relativePath';

            //jQuery code to redirect a page or URL
            $(document).ready(function(){
                //var url = "http://code.shouttoday.com";
                //$(location).attr('href',url);
                // $(window).attr('location',url)
                //$(location).prop('href', url)
            });
        </script>
    </body>
</html>

使用 :

function redirect(a) {
    location = a
}

并称之为:redirect([url]);

没必要href之后location,因为它是隐含的。