document.forms 输入名称选择器在 JavaScript DOM 中如何工作?

How does the document.forms name selector for inputs work in JavaScript DOM?

在 Meteor 的 todo 应用教程中,有这个例子:

  Template.body.events({
    "submit .new-task": function (event) {
      // Prevent default browser form submit
      event.preventDefault();

      // Get value from form element
      var text = event.target.text.value;

      [...]
    }
  });

这是相关的 HTML :

  <form class="new-task">
    <input type="text" name="text" placeholder="Type to add new tasks" />
  </form>

令我惊讶的是 event.target.text.value 是一个有效的选择器,尽管 text 不是 event.target 对象的 属性。

有人可以向我解释为什么有效吗?

在您的代码片段的上下文中,event.target 是对表单的引用。

event.target.text 是对名称为 "text" 的表单元素的引用,它被传递给表单元素内输入集合中的回调。

Note: This is a unique attribute of forms, for backwards-compatibility with the pre-DOM document.forms collection, which references forms and their input elements by name rather than by id. For example, you can reference the search form input on this page using document.forms.search.q