-
平時HTML中的a標簽是我們十分喜愛使用的,但是就是這樣的簡單基礎的標簽有時候會出現我們意想不到的問題。
-
首先來一段測試,以復現問題,使用一堆url,動態創建多個a標簽,撰寫如下所示的代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>艾孜爾江的測試頁面</title>
</head>
<body>
<ul id="myid"></ul>
</body>
<script type="text/javascript">
let urls = [
"www.baidu.com",
"www.sogo.com",
"www.bing.com",
"www.163.com",
];
let str = '';
for (let i = 0; i < urls.length; i++) {
let content = urls[i];
str += ' <h3>' + ("Page" + i) + '</h3>';
str += ' <a href="' + urls[i] + '" target=_blank' + '>' + '第' + i + '個' + '</a>';
}
document.getElementById("myid").innerHTML = str;
</script>
</html>
-
我們以為上面的寫法非常正確,URL加進去了,而且我們的創建效果也實現了,頁面效果如下:
-
但是當我們點擊的那一時刻,我們發現頁面跳轉到
MY_SERVER_IP + / + URL
,而不是直接跳轉到指定的URL頁面。 -
經過一番檢查,發現原來是沒有將URL寫規范,只要在所有URL的前面加上
https
我們就可以實現直接跳轉到指定頁面的需求,最后的代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>艾孜爾江的測試頁面</title>
</head>
<body>
<ul id="myid"></ul>
</body>
<script type="text/javascript">
let urls = [
"https://www.baidu.com",
"https://www.sogo.com",
"https://www.bing.com",
"https://www.163.com",
];
let str = '';
for (let i = 0; i < urls.length; i++) {
let content = urls[i];
str += ' <h3>' + ("Page" + i) + '</h3>';
str += ' <a href="' + urls[i] + '" target=_blank' + '>' + '第' + i + '個' + '</a>';
}
document.getElementById("myid").innerHTML = str;
</script>
</html>
作者:艾孜爾江