JavaScript 如何重定向到另一个网页
在本文中,我们将了解如何使用JavaScript重定向网页到另一个页面,并通过示例了解其实现方式。window.location对象存储页面的位置或URL,我们可以使用window.location来重定向到另一个页面。
使用JavaScript可以有多种方法重定向到另一个网页。以下是其中一些方法:
- location.href: 用于设置或返回当前页面的完整URL。
- location.replace(): 用指定的页面替换当前文档。
- location.assign(): 用于加载新文档。
语法:
location.href="URL"
or
location.replace("URL")
or
location.assign("URL")
参数: 它接受一个参数 URL 是必需的。它用于指定新网页的引用。
返回值: 没有返回值。
示例 1: 这个示例说明了使用 location.href 属性。
<!DOCTYPE html>
<html>
<body>
<h2>Welcome to GeeksforGeeks</h2>
<p>This is the example of <i>location.href</i> way. </p>
<button onclick="myFunc()">Click me</button>
<!--script to redirect to another webpage-->
<script>
function myFunc() {
window.location.href = "https://www.geeksforgeeks.org/";
}
</script>
</body>
</html>
输出:

示例2: 这是一个使用 location.replace() 方法的示例。
<!DOCTYPE html>
<html>
<body>
<h2>Welcome to GeeksforGeeks</h2>
<p>This is the example of <i>location.replace</i> method. </p>
<button onclick="myFunc()">Click me</button>
<!--script to redirect to another webpage-->
<script>
function myFunc() {
location.replace("https://www.geeksforgeeks.org/");
}
</script>
</body>
</html>
输出:

示例 3: 此示例使用 location.assign() 方法。
<!DOCTYPE html>
<html>
<body>
<h1>GeeksforGeeks</h1>
<h2>Location assign() Method</h2>
<button onclick="load()">Click Here!</button>
<!-- Script to use Location assign() Method -->
<script>
function load() {
location.assign(
"https://ide.geeksforgeeks.org/index.php");
}
</script>
</body>
</html>
输出:

注意: 所有方法的输出结果都一样,但是 location.replace() 方法会从文档历史记录中移除当前文档的URL。因此,如果您希望有返回原始文档的选项,最好使用 location.assign() 方法。
极客教程