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


当前回答

这样做有三个主要途径,

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

还有...

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

最后一个是最好的, 用于传统的重定向, 因为它不会保存您在搜索历史中被重定向之前的页面。 但是, 如果您只想用 JavaScript 打开一个标签, 您可以使用上述任何选项 。1

爱迪特:window前缀是可选的 。

其他回答

标注描述 :

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

您需要在代码中输入这条线 :

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

如果你没有jQuery, 和JavaScript一起去:

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

这就是我如何使用它。

   window.location.replace('yourPage.aspx');   
   // If you're on root and redirection page is also on the root

   window.location.replace(window.location.host + '/subDirectory/yourPage.aspx');

   // If you're in sub directory and redirection page is also in some other sub directory.

JavaScript 非常广泛。 如果您想要跳转到另一页, 您有三个选项 。

 window.location.href='otherpage.com';
 window.location.assign('otherpage.com');
 //and...

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

当您想要移动到另一页时, 如果这是您的要求, 您可以使用其中的任何内容 。 但是所有三种选择都局限于不同的情况 。 请按照您的要求明智地选择 。

如果您有兴趣了解更多有关这个概念的知识,可以更深入地了解。

window.location.href; // Returns the href (URL) of the current page
window.location.hostname; // Returns the domain name of the web host
window.location.pathname; // Returns the path and filename of the current page
window.location.protocol; // Returns the web protocol used (http: or https:)
window.location.assign; // Loads a new document
window.location.replace; // RReplace the current location with new one.

根据我的工作经验 JavaScript 更适合重新定位

它取决于您要如何更改地址。 如果您想要在用户历史中登录您的网站, 请使用window.location.href='ur website';否则在不记录历史的情况下使用window.location.replace("your website");.