上一篇處理了單選鈕與核取方塊,這次換成下拉選單(select)與頁面連結的屬性。
<html>
<head>
<title>下拉選單</title>
<script language="javascript">
function display()
{
if (document.selectForm.team.selectedIndex == 0) // 判斷是否做了選擇
{
alert("您沒有做選擇!");
}
else
{
var index = document.selectForm.team.selectedIndex; // 目前選項的索引
alert("您選擇的球隊是:" + document.selectForm.team.options[index].value);
}
}
</script>
</head>
<body>
<div align="center">
<form action="" method="post" name="selectForm" id="selectForm">
<table width="70%" border="0">
<tr><td>請選擇喜歡的球隊:</td></tr>
<tr>
<td>
<select name="team">
<option value="0">--未選擇--</option>
<option value="巴塞羅那">巴塞羅那</option>
<option value="AC米蘭">AC米蘭</option>
<option value="尤文圖斯">尤文圖斯</option>
<option value="曼徹斯特聯">曼徹斯特聯</option>
<option value="切爾西">切爾西</option>
</select>
</td>
</tr>
<tr>
<td>
<input name="look" type="button" id="look" value="單擊查看" onClick="display()">
</td>
</tr>
</table>
</form>
<a href="https://www.baidu.com" name="baidu" target="_blank">有問題百度一下</a><br><br>
<a href="https://www.google.com" name="google" target="_blank">Google 也可以</a><br><br>
<script language="javascript">
document.write("第一個連結的資訊:<br>");
document.write("<b>href:</b>" + document.links[0].href + "<br>");
// 接著還可以讀 pathname、hostname、target 等屬性
</script>
</div>
</body>
</html>
selectedIndex:目前選中項目的索引,從 0 開始。範例刻意把「--未選擇--」放在第一個選項,因此只要 selectedIndex 是 0,就代表使用者什麼都沒挑——這是常見的「佔位選項」技巧。
options:所有選項的集合。用 options[index] 取得該項目後,就能讀它的 value 或 text。要特別注意這兩者的差別:value 是送給伺服器的值,text 是畫面上顯示的文字。若 option 沒有寫 value 屬性,瀏覽器會自動用它的文字內容當成 value。
其實要取得目前選中的值,有更簡潔的寫法:
var sel = document.selectForm.team;
alert(sel.options[sel.selectedIndex].value);
// 或者直接
alert(sel.value);
document.links 會收集頁面上所有的 a 標籤與帶 href 的 area 標籤,用索引即可逐一讀取。除了 href,常見的屬性還有 protocol、hostname、pathname、search、hash、target 等。
要注意 href 讀出來一定是「解析後的絕對網址」。即使原始碼寫的是 /about.html,讀到的也會是 https://你的網域/about.html。若想取得原始寫法,得自己從 getAttribute('href') 拿。
target="_blank" 建議再加上 rel="noopener noreferrer",避免新開的頁面透過 window.opener 反向操作你的頁面,這是實際存在過的安全風險。
另外,範例中的 table 排版與 align 屬性都屬於舊式寫法。這類「表單 + 版面」的組合,今天用 CSS 會乾淨得多,也更方便做響應式設計。