如何使用jQuery或纯JavaScript将用户从一个页面重定向到另一个页面?
不需要jQuery。你可以这样做:
window.open("URL","_self","","")
很容易!
发起HTTP请求的最佳方式是使用document.location.href.replace('URL')
。
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; // Replace the current location with new one.
window.location.href="http://google.com";
window.location.replace("http://google.com");
$(location).attr('href', 'http://google.com');
jQuery.fn.redirectTo = function(url){
window.location.href = url;
}
jQuery(window).redirectTo("http://google.com");
您可以通过以下方式在jQuery中进行重定向:
$(location).attr('href', 'http://yourPage.com/');
首先要正确编写代码。如果你想从你的应用程序导航到另一个链接,那么这里是代码:
window.location.href = "http://www.google.com";
如果您想在应用程序内导航页面,那么我也有代码,如果需要的话。
第一种方法
这是重定向页面的jQuery代码。由于我将此代码放在$(document).ready()函数中,因此它将在页面加载时立即执行。
var url = "http://stackoverflow.com";
$(location).attr('href',url);
甚至可以直接将URL传递给attr()方法,而不是使用变量。
第二种方式
window.location.href="http://stackoverflow.com";
你也可以像这样编写代码(两种方式在内部是相同的):
window.location="http://stackoverflow.com";
// Doesn't put originating page in history
window.location.replace("http://stackoverflow.com");
location.assign()
方法在浏览器窗口中加载一个新的文档。window.location.assign("http://stackoverflow.com");
assign()
和replace()
方法的区别在于,location.replace()
方法会从文档历史记录中删除当前URL,因此无法返回到原始文档。在这种情况下,您不能使用浏览器的后退按钮。如果要避免这种情况,应该使用location.assign()
方法,因为它会在浏览器中加载一个新文档。
第五种方式
类似于attr()
方法(jQuery 1.6之后引入)
var url = "http://stackoverflow.com";
$(location).prop('href', url);
window.location.href="http://google.com";
window.location.replace("page1.html");
Javascript:
window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');
JQuery:
var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window
$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")
请不要杀了我,这只是一个笑话。这是一个笑话。这只是一个笑话。
就问题而言,这个答案“提供了一个使用jQuery的解决方案”,这在本例中意味着以某种方式将其强制纳入等式中。
Ferrybig 显然需要对这个笑话进行解释(仍然是开玩笑,我相信审核表上的选择有限),所以话不多说:
其他答案在location
或window
对象上不必要地使用了 jQuery 的 attr()
。
这个答案也滥用了它,但是以一种更荒谬的方式。它没有使用它来设置位置,而是使用 attr()
来检索一个设置位置的函数。
该函数名为 jQueryCode
,尽管它与 jQuery 没有任何关系,并且在调用一个名为 somethingCode
的函数时,特别是当 something 不是一种语言时,这种做法非常可怕。
“85字节”是对代码高尔夫球的参考。高尔夫球显然不是你在代码高尔夫球之外应该做的事情,而且此答案显然并没有真正进行高尔夫压缩。
基本上,很尴尬。