aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/htmlcollection/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/zh-cn/web/api/htmlcollection/index.html')
-rw-r--r--files/zh-cn/web/api/htmlcollection/index.html66
1 files changed, 66 insertions, 0 deletions
diff --git a/files/zh-cn/web/api/htmlcollection/index.html b/files/zh-cn/web/api/htmlcollection/index.html
new file mode 100644
index 0000000000..07358016cb
--- /dev/null
+++ b/files/zh-cn/web/api/htmlcollection/index.html
@@ -0,0 +1,66 @@
+---
+title: HTMLCollection
+slug: Web/API/HTMLCollection
+translation_of: Web/API/HTMLCollection
+---
+<p>{{ APIRef("HTML DOM") }}</p>
+
+<p><strong><code>HTMLCollection</code></strong> 接口表示一个包含了元素(元素顺序为文档流中的顺序)的通用集合(generic collection),还提供了用来从该集合中选择元素的方法和属性。</p>
+
+<div class="note"><strong>注意:由于历史原因(DOM4之前,实现该接口的集合只能包含 HTML 元素),该接口被称为 </strong><code>HTMLCollection</code>。</div>
+
+<p>HTML DOM 中的 <code>HTMLCollection</code> 是即时更新的(live);当其所包含的文档结构发生改变时,它会自动更新。</p>
+
+<h2 id="属性">属性</h2>
+
+<dl>
+ <dt>{{domxref("HTMLCollection.length")}} {{readonlyInline}}</dt>
+ <dd>返回集合当中子元素的数目。</dd>
+</dl>
+
+<h2 id="方法">方法</h2>
+
+<dl>
+ <dt>{{domxref("HTMLCollection.item()")}}</dt>
+ <dd>根据给定的索引(从0开始),返回具体的节点。如果索引超出了范围,则返回 <code>null</code>。</dd>
+ <dt>{{domxref("HTMLCollection.namedItem()")}}</dt>
+ <dd>根据 Id 返回指定节点,或者作为备用,根据字符串所表示的 <code>name</code> 属性来匹配。根据 name 匹配只能作为最后的依赖,并且只有当被引用的元素支持 <code>name</code> 属性时才能被匹配。如果不存在符合给定 name 的节点,则返回 <code>null</code>。</dd>
+</dl>
+
+<h2 id="在_JavaScript_中使用">在 JavaScript 中使用</h2>
+
+<p>在 JavaScript 中,为了获取给定的 HTMLCollection 的元素,可以使用方括号语法来代替直接调用 <code>item()</code> 或 <code>namedItem()</code> 方法。在方括号中,数值如同 <code>item()</code>,字符串值如同 <code>namedItem()。</code></p>
+
+<p>例如,假定在文档中有一个 <code>&lt;form&gt;</code> 元素,且它的 <code>id</code> 是 <code>"myForm"</code>:</p>
+
+<pre class="brush:js">var elem1, elem2;
+
+// document.forms 是一个 HTMLCollection
+
+elem1 = document.forms[0];
+elem2 = document.forms.item(0);
+
+alert(elem1 === elem2); // 显示 "true"
+
+elem1 = document.forms["myForm"];
+elem2 = document.forms.namedItem("myForm");
+
+alert(elem1 === elem2); // 显示 "true"</pre>
+
+<h2 id="浏览器兼容性">浏览器兼容性</h2>
+
+<p>当使用字符串作为 namedItem 的参数,且匹配的元素多于一个时,不同的浏览器表现不同。Firefox 8 表现如同 DOM 2 和 DOM 4 说明的,返回第一个匹配的元素。而 Webkit 浏览器和 IE 返回另外一个 HTMLCollection,Opera 返回一个包含所有元素的 {{domxref("NodeList")}}。</p>
+
+<h2 id="规范">规范</h2>
+
+<ul>
+ <li><a href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506" title="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506">DOM Level 2 HTML, Section 1.4, Miscellaneous Object Definitions</a></li>
+ <li><a href="http://www.w3.org/TR/domcore/#interface-htmlcollection" title="http://www.w3.org/TR/domcore/#interface-htmlcollection">DOM4: HTMLCollection</a></li>
+</ul>
+
+<h2 id="相关链接">相关链接</h2>
+
+<ul>
+ <li>{{domxref("NodeList")}}</li>
+ <li>{{domxref("HTMLFormControlsCollection")}}, {{domxref("HTMLOptionsCollection")}}</li>
+</ul>