document.anchors 可返回文件中所有 Anchor 物件的參考。錨點常用於頁內跳轉或章節導覽,透過這個集合可以更方便地管理頁面中的錨點。
document.anchors[]你可以透過索引取得特定錨點,也可以使用 length 取得錨點數量。
<html>
<body>
<a name="first">First anchor</a><br />
<a name="second">Second anchor</a><br />
<a name="third">Third anchor</a><br />
<br />
Number of anchors in this document:
<script type="text/javascript">
document.write(document.anchors.length);
</script>
</body>
</html>這段程式會顯示文件中錨點的數量。
若頁面有長篇內容,可以建立多個錨點,再用 document.anchors 搭配迴圈動態產生導覽連結。
for (var i = 0; i < document.anchors.length; i++) {
document.write(document.anchors[i].name + "<br />");
}這在說明文件、 FAQ、商品條款等長頁面中很實用。