我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?


当前回答

有三种主要方法可以做到这一点,

window.location.href='blaah.com';
window.location.assign('blaah.com');

和...

window.location.replace('blaah.com');

最后一个是最好的,对于一个传统的重定向,因为它不会保存你去的页面,然后在你的搜索历史中重定向。

EDIT:窗口预定是可选的。

其他回答

如果你正在尝试生成包数据,有几个选项,你如何做到这一点,你可以生成单独的链接,每个页面你想能够直接到。

<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...

请注意,示例中的当前页面在代码和CSS中以不同的方式处理。

如果您希望通过 AJAX 更改已支付的数据,这就是 jQuery 会进入的地方. 您所做的就是将一个点击处理器添加到相应不同页面的每个 anchor 标签. 这个点击处理器会引用一些 jQuery 代码,并通过 AJAX 获取下一个页面并更新新数据的表。

$(document).ready( function() {
    $('a.pager-link').click( function() {
        var page = $(this).attr('href').split(/\?/)[1];
        $.ajax({
            type: 'POST',
            url: '/path-to-service',
            data: page,
            success: function(content) {
               $('#myTable').html(content);  // replace
            }
        });
        return false; // to stop link
    });
});

一个不只是使用jQuery重定向

jQuery 不需要, window.location.replace(...) 最好是模拟一个 HTTP 重定向。

window.location.replace(...) 比使用 window.location.href 更好,因为 replace() 不保留起源页面在会话历史中,这意味着用户不会陷入无止境后按钮故障。

如果你想模拟某人点击链接,使用 location.href

如果您想模拟一个 HTTP 重定向,请使用 location.replace。

例如:

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

您可以在 jQuery 中以以下方式重定向:

$(location).attr('href', 'http://yourPage.com/');

您需要在代码中插入此行:

$(location).attr("href","http://stackoverflow.com");

如果您没有 jQuery,请使用 JavaScript:

window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");

JavaScript 的内容:

window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');

吉克里:

var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window