当引用 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:
Let result be an empty list.
For each element represented by the collection, in tree order:
If element has an ID which is not in result, append element’s ID to result.
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’sname
attribute value to result.Return result.
另请注意 NodeList与 HTMLCollection 属于同一部分 (Old-style collections)。见 NodeList在 MDN 网络文档上。
前面提到的
[LegacyUnenumerableNamedProperties]
(正如 @Kaiido 指出的那样)仅表示命名属性是不可枚举的(即,使用 Array.from
将仅返回索引项)。
关于javascript - 关于 HTMLCollections 和命名属性的问题,继续使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69736817/