blob: 3ad55692477d137674c21e6f355905ba8f6a7276 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
---
title: document.anchors
slug: Web/API/Document/anchors
translation_of: Web/API/Document/anchors
---
<p>{{APIRef("DOM")}}</p>
<p> </p>
<p>{{deprecated_header()}}</p>
<p> </p>
<h3 id="Summary" name="Summary">概述</h3>
<p><code>anchors</code>属性返回当前文档中的所有锚点元素.</p>
<h3 id="Syntax" name="Syntax">语法</h3>
<pre class="eval"><em>nodeList</em> = document.anchors
</pre>
<h3 id="Example" name="Example">例子</h3>
<pre class="brush: js">if ( document.anchors.length >= 5 ) {
dump("dump found too many anchors");
window.location = "http<span class="nowiki">:</span>//www.google.com";
}
</pre>
<p>下例自动生成一个目录列表,包含了到每个段落的锚点.</p>
<pre class="brush: js"><!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" charset="utf-8">
function init() {
var toc = document.getElementById("toc");
var i, li, newAnchor;
for (i = 0; i < document.anchors.length; i++) {
li = document.createElement("li");
newAnchor = document.createElement('a');
newAnchor.href = "#" + document.anchors[i].name;
newAnchor.innerHTML = document.anchors[i].text;
li.appendChild(newAnchor);
toc.appendChild(li);
}
}
</script>
</head>
<body onload="init()">
<h1>Title</h1>
<a name="contents"><h2>Contents</h2></a>
<ul id="toc"></ul>
<a name="plants"><h2>Plants</h2></a>
<ol>
<li>Apples</li>
<li>Oranges</li>
<li>Pears</li>
</ol>
<a name="veggies"><h2>Veggies</h2></a>
<ol>
<li>Carrots</li>
<li>Celery</li>
<li>Beats</li>
</ol>
</body>
</html>
</pre>
<p><a href="https://jsfiddle.net/S4yNp">在JSFiddle中查看</a></p>
<h3 id="Notes" name="Notes">备注</h3>
<p>由于向后兼容的原因,该属性只返回那些拥有<code>name属性的a元素,而不是那些拥有</code><code>id</code>属性的<code>a</code>元素.</p>
<h3 id="Specification" name="Specification">规范</h3>
<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-7577272">DOM Level 2 HTML: anchors</a></p>
<p>{{ languages( { "es": "es/DOM/document.anchors", "pl": "pl/DOM/document.anchors", "ja": "ja/DOM/document.anchors" , "en": "en/DOM/document.anchors" } ) }}</p>
|