aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/document/anchors/index.html
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 &gt;= 5 ) {
    dump("dump found too many anchors");
    window.location = "http<span class="nowiki">:</span>//www.google.com";
}
</pre>

<p>下例自动生成一个目录列表,包含了到每个段落的锚点.</p>

<pre class="brush: js">&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;script type="text/javascript" charset="utf-8"&gt;
    function init() {
        var toc = document.getElementById("toc");
        var i, li, newAnchor;
        for (i = 0; i &lt; 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);
        }
    }

    &lt;/script&gt;
&lt;/head&gt;
&lt;body onload="init()"&gt;

&lt;h1&gt;Title&lt;/h1&gt;
&lt;a name="contents"&gt;&lt;h2&gt;Contents&lt;/h2&gt;&lt;/a&gt;
&lt;ul id="toc"&gt;&lt;/ul&gt;

&lt;a name="plants"&gt;&lt;h2&gt;Plants&lt;/h2&gt;&lt;/a&gt;
&lt;ol&gt;
    &lt;li&gt;Apples&lt;/li&gt;
    &lt;li&gt;Oranges&lt;/li&gt;
    &lt;li&gt;Pears&lt;/li&gt;
&lt;/ol&gt;

&lt;a name="veggies"&gt;&lt;h2&gt;Veggies&lt;/h2&gt;&lt;/a&gt;
&lt;ol&gt;
    &lt;li&gt;Carrots&lt;/li&gt;
    &lt;li&gt;Celery&lt;/li&gt;
    &lt;li&gt;Beats&lt;/li&gt;
&lt;/ol&gt;

&lt;/body&gt;
&lt;/html&gt;
</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>