我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
基本上,jQuery只是一个JavaScript框架,在这种情况下,你只能使用纯粹的JavaScript,所以在这种情况下,你有3个选项使用VanillaJavaScript:
使用位置替换,这将取代当前页面历史,这意味着无法使用后按钮返回原始页面。
window.location.replace("http://stackoverflow.com");
2) 使用位置指定,这将为您保存历史,并使用返回按钮,您可以返回原始页面:
window.location.assign("http://stackoverflow.com");
3)我建议使用上述方式之一,但这可能是使用纯粹的JavaScript的第三个选项:
window.location.href="http://stackoverflow.com";
您也可以在 jQuery 中编写一个函数来处理它,但不推荐,因为它只是一个线纯的JavaScript函数,如果您已经在窗口范围内,也可以使用上面的所有函数没有窗口,例如 window.location.replace(“http://stackoverflow.com”);可以是 location.replace(“http://stackoverflow.com”);
我在下面的图像中展示了所有这些:
此分類上一篇
其他回答
它适用于每个浏览器:
window.location.href = 'your_url';
在 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>
使用 jQuery 功能:
$.extend({
redirectPost: function(location, args) {
var form = '';
$.each(args, function(key, value) {
form += '<input type="hidden" name="' + key + '" value="' + value + '">';
});
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
}
});
在你的代码中,你使用它如下:
$.redirectPost("addPhotos.php", {pimreference: $("#pimreference").val(), tag: $("#tag").val()});
与 jQuery 合作:
$(window).attr("location", "http://google.fr");
我只是添加另一种方式:
要将您的网站的任何特定页面/链接转向另一个页面,只需添加此代码行:
<script>
if(window.location.href == 'old_url')
{
window.location.href="new_url";
}
// Another URL redirect
if(window.location.href == 'old_url2')
{
window.location.href="new_url2";
}
</script>
作为现实生活的例子,
<script>
if(window.location.href == 'https://old-site.com')
{
window.location.href="https://new-site.com";
}
// Another URL redirect
if(window.location.href == 'https://old-site.com/simple-post.html')
{
window.location.href="https://new-site.com/simple-post.html";
}
</script>
使用这个简单的代码,您可以重新引导完整的网站或任何单页。