javascript - 关于 HTMLCollections 和命名属性的问题,继续使用?

标签 javascript html dom standards htmlcollection

当引用 HTML 表单中的元素时,我经常使用 name 属性的名称/值。所以,如果表格的名称是“form01”,我指的是表格写成document.forms.form01 .这是一个例子:

let title = document.forms.form01.title;
console.log(title.value);
<form name="form01">
  <input type="text" name="title" value="Hello World">
</form>
document.forms是一个 HTMLCollection,但在 DOM Standard #interface-htmlcollection 的文档中它没有说明在这样的集合上直接使用名称作为属性(我认为它被称为“命名属性”)的可能性——就像我使用 document.forms.form01 时一样。引用表单元素。相反,文档实际上指出这是“历史文物”——那么,我应该避免使用它吗?
你能帮我找到这方面的文件吗?要么它是一个可以使用的(很好的)功能,要么它是应该避免的。

最佳答案

如果它没有被标记为弃用或过时的功能,您绝对可以继续使用它!
有关 HTMLCollection 的 MDN Web 文档的更多详细信息声明如下:

The HTMLCollection interface represents a generic collection (array-like object similar to arguments) of elements (in document order) and offers methods and properties for selecting from the list.



至于 HTMLCollection 中的命名属性(如 @Kaiido 所指出的),this section状态:

The supported property names are the values from the list returned by these steps:

  1. Let result be an empty list.

  2. For each element represented by the collection, in tree order:

    1. If element has an ID which is not in result, append element’s ID to result.

    2. If element is in the HTML namespace and has a name attribute whose value is neither the empty string nor is in result, append element’s name attribute value to result.

  3. Return result.


另请注意 NodeList与 HTMLCollection 属于同一部分 (Old-style collections)。见 NodeList在 MDN 网络文档上。

前面提到的 [LegacyUnenumerableNamedProperties] (正如 @Kaiido 指出的那样)仅表示命名属性是不可枚举的(即,使用 Array.from 将仅返回索引项)。

关于javascript - 关于 HTMLCollections 和命名属性的问题,继续使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69736817/

相关文章:

javascript - 如何在 Javascript 中像 php 一样使用 for 循环

javascript - 如何将HTML数据从 Node js发送到前端?

javascript - 不接收负数

html - 我的网站如何在桌面和移动设备上有不同的 View float 操作按钮?

dom - 检索 DOM 文本节点位置

javascript - Coffeescript:跳出 forEach 循环

javascript - 单击选项中的选项时,如何更改音频源?

javascript - 使用 CDN 与 NPM 安装库

Javascript - 如何将 jQuery 对象(表)传递给 Web Worker?

javascript - CoffeeScript - 不允许在 Angular 表达式中引用 DOM 节点