在JavaScript中有好幾種方法可以重定向到另一個網頁,下面本篇文章就來給大家介紹一些使用JavaScript重定向到另一個網頁的方法,希望對大家有所幫助。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicGcq5CM0MDMkJTZ0cTNkBjYxQWNvwlNwAzLcBDMw8CXwADMvwVZsNWa0JXYvwFZh9GbwV3Lc52YuAHaw5yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
如何使用JavaScript重定向到其他網頁?
使用JavaScript重定向到其他網頁的一些方法:
- location.href
- location.replace()
- location.assign()
文法:
location.href="URL"
//或者
location.replace("URL")
//或者
location.assign("URL")
參數:接受單個參數的URL,這是必需的。用于指定新網頁的引用。
傳回值:無傳回值。
示例1:使用location.href屬性重定向到其他網頁
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>這是<i>location.href</i>方式的示例</p>
<button onclick="myFunc()">點選這裡</button>
<!--重定向到其他網頁的腳本-->
<script>
function myFunc() {
window.location.href="https://www.html.cn";
}
</script>
</body>
</html>
效果圖:
示例2:使用location.replace()方法重定向到其他網頁
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>這是<i>location.replace()</i>方式的示例</p>
<button onclick="myFunc()">點選這裡</button>
<!--重定向到其他網頁的腳本-->
<script>
function myFunc() {
location.replace("https://www.html.cn");
}
</script>
</body>
</html>
示例3:使用location.assign()方法重定向到其他網頁
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>這是<i>location.assign()</i>方式的示例</p>
<button onclick="myFunc()">點選這裡</button>
<!--重定向到其他網頁的腳本-->
<script>
function myFunc() {
location.assign("https://www.html.cn");
}
</script>
</body>
</html>
- Google Chrome
- Apple Safari
- Firefox
- Opera
-
Edge
原文位址:如何使用JavaScript重定向到其他網頁?