DIV CSS 佈局教程網

取得網頁中第一個連結的 id:document.links[0]
編輯:關於JavaScript     

用 document.links 取得所有超連結後,索引 0 就是文件中最早出現的那一個,讀它的 id 屬性即可。

<!DOCTYPE html>
<html>
<body>
<h1>sharejs.com</h1>

<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">
<map name="planetmap">
  <area id="sun" shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
  <area id="mercury" shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
  <area id="venus" shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>

<p><a id="javascript" href="/js/">JavaScript Tutorial</a></p>

<p>第一個連結的 id:
<script>
  document.write(document.links[0].id);
</script>
</p>
</body>
</html>

輸出會是 sun,因為 <area id="sun"> 在文件中出現的位置比那個 <a> 更早。這一點值得注意:document.links 依文件中的出現順序排列,而不是依元素類型分組,所以混用 <area> 與 <a> 時,索引結果可能不如直覺。

更穩健的取法

依索引取值的前提是「頁面結構不會變」。若你的目標明確,直接定位會安全得多:

// 已知 id
document.getElementById('javascript');

// 取第一個真正的超連結(排除 area)
document.querySelector('a[href]');

// 取導覽區內的第一個連結
document.querySelector('nav a');

動手前檢查是否存在

var first = document.links[0];
if (first && first.id) {
  console.log(first.id);
}

頁面沒有任何連結時,document.links[0] 是 undefined,直接取 .id 會拋 TypeError。用 if guards 或可選串接 document.links[0]?.id 都能避免這個問題。

另外提醒:id 的值若含有空白或特殊字元,在 CSS 選取與 querySelector 中都需要跳脫處理。延續上一篇提到的原則,id 請用單一、不含空白的識別字。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved