我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
在 jQuery 中,使用 $(位置)。attr('href', url):
$(document).ready(function(){ var url = "https://www.youtube.com/watch?v=JwMKRevYa_M"; $(location).attr('href', url); // 使用此 }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
在原始JavaScript中,有几种方法可以实现:
window.location.href="https://www.youtube.com/watch?v=JwMKRevYa_M";
href 属性明确设定。
window.location = "http://www.GameOfThrones.com";
因为 window.location 返回一个对象,默认设置其.href 属性。
window.location.replace("http://www.stackoverflow.com");
将现行窗口的位置替换为新窗口。
self.location = "http://www.somewebsite.com";
设置当前窗口本身的位置。
下面是JavaScript在一定时间(3秒)后重新引导的例子:
<script> setTimeout(函数() { window.location.href = “https://www.youtube.com/”; }, 3000); </script>
其他回答
在JavaScript和jQuery中,我们可以使用以下代码将一页转向另一页:
window.location.href="http://google.com";
window.location.replace("page1.html");
<script type="text/javascript">
if(window.location.href === "http://stackoverflow.com") {
window.location.replace("https://www.google.co.in/");
}
</script>
它适用于每个浏览器:
window.location.href = 'your_url';
<script type="text/javascript">
var url = "https://yourdomain.com";
// IE8 and lower fix
if (navigator.userAgent.match(/MSIE\s(?!9.0)/))
{
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
// All other browsers
else { window.location.replace(url); }
</script>
在 PHP、HTML 或 jQuery 部分后写下下面的代码,如果在 PHP 或 HTML 部分中间,则使用 <script> 标签。
location.href = "http://google.com"