JavaScript 如何让浏览器导航到URL
作为一个web开发人员,你可能需要从你的JavaScript代码中导航到特定的URL。这可以通过访问浏览器的window对象并使用其中一种可用的方法来改变当前URL来实现。
在JavaScript中,有几种导航到URL的方法。最常用的方法有:
使用window.location.href: 这种方法用于获取或设置当前页面的整个URL。它返回一个包含当前URL的字符串,也可以通过将其设置为所需的值来导航到新的URL。
方法:使用window.location.href: 这种方法将当前窗口的整个URL设置为指定的URL。这种方法会在同一个窗口中加载新的URL并在浏览器的历史记录中添加一个条目。JavaScript中的window.location属性用于获取或设置浏览器窗口的当前URL。它是一个只读属性,包含有关当前URL的信息,包括协议、域名、端口号、路径和查询字符串。在这个例子中,href属性设置为“#”,以防止浏览器在点击链接时导航到其他页面。相反,使用onclick属性来执行JavaScript函数,将window.location.href属性设置为所需的URL。
语法:
window.location.href = "https://www.gfg.com";
示例: 使用按钮时,此 HTML 代码链接到 GeeksforGeeks 的主页。
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Linking to GeeksforGeeks
using JavaScript
</title>
</head>
<body>
<h1>
Linking to GeeksforGeeks using JavaScript
</h1>
<h3>Using 'window.location.href' method</h3>
<p>
Click the button below to go
to the GeeksforGeeks website:
</p>
<button onclick="goToGeeksforGeeks()">
Go to GeeksforGeeks
</button>
<script>
function goToGeeksforGeeks() {
window.location.href =
"https://write.geeksforgeeks.org/";
}
</script>
</body>
</html>
输出:
使用 window.location.assign() 方法: 该方法用于通过设置当前窗口的location.href属性的值来加载新文档。它类似于设置window.location.href,但还允许您使用history对象向浏览器的历史记录添加新条目。
方法:使用 window.location.assign(): 这种方法与设置window.location.href相似。区别在于,该方法还允许您导航到特定的URL,同时保留当前页面的历史记录。这意味着返回按钮仍然有效,并将用户带回到上一页。
语法:
window.location.assign("https://www.gfg.com");
示例: 当按钮被使用时,此 HTML 代码链接到 GeeksforGeeks 主页。
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Linking to GeeksforGeeks
using JavaScript
</title>
</head>
<body>
<h1>
Linking to GeeksforGeeks
using JavaScript
</h1>
<h3>Using 'window.location.assign' method</h3>
<p>
Click the button below to go to
the GeeksforGeeks website:
</p>
<button onclick="goToGeeksforGeeks()">
Go to GeeksforGeeks
</button>
<script>
function goToGeeksforGeeks() {
window.location.assign(
"https://write.geeksforgeeks.org/");
}
</script>
</body>
</html>
输出:
使用window.location.replace()方法: 该方法类似于window.location.assign(),但它不会在浏览器的历史记录中创建新的条目。相反,它将当前条目替换为新的条目,使得无法使用返回按钮返回到上一页。
方法:使用window.location.replace()方法: 该方法也导航到特定的URL,但不会在浏览器的历史记录中添加记录。这意味着用户无法使用返回按钮导航到前一个页面。
语法:
window.location.replace("https://www.example.com");
示例: 当使用按钮时,此HTML代码与GeeksforGeeks首页链接。
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Linking to GeeksforGeeks
using JavaScript
</title>
</head>
<body>
<h1>
Linking to GeeksforGeeks
using JavaScript
</h1>
<h3>Using 'window.location.replace' method</h3>
<p>
Click the button below to go to
the GeeksforGeeks website:
</p>
<button onclick="goToGeeksforGeeks()">
Go to GeeksforGeeks
</button>
<script>
function goToGeeksforGeeks() {
window.location.replace(
"https://write.geeksforgeeks.org/");
}
</script>
</body>
</html>
输出:
此方法与其他两种方法不同,不允许用户返回到前一页。