javascript - 为什么不需要 getElementById 来获取表单中的 ID

标签 javascript html

我正在努力学习 JavaScript,以便能够将它与 jQuery 进行比较。我一直在寻找一种解释(或证明我做对了的东西)为什么表单输入中的 ID 被视为名称属性(以我们选择它们的方式)

<form id="myskills">
    <input type="text" id="skillpg">
</form>

如果我想通过 ID 获取输入,我会这样做:

document.getElementById('skillpg');

我错误地发现我也可以通过这样做来选择相同的输入

document.getElementById('myskills').skillpg

在我看来,代码使用 name="skillpg" 而不是 ID 名称获取输入元素。

在我写这个问题时,听起来我应该接受它并继续前进。但是是否有理由不使用这种方式而只是坚持使用 getElementById 或使用名称属性而不是 ID?

谢谢

最佳答案

HTMLFormElement 起有效为此有一个特殊的 setter/getter :

interface HTMLFormElement : HTMLElement {  
    ...
  readonly attribute HTMLFormControlsCollection elements;
  readonly attribute long length;
  getter Element (unsigned long index);
  getter (RadioNodeList or Element) (DOMString name);
};

getter 将在您使用 form["name"] 时使用。由于 form.name === form["name"],一切都很好,因为 algorithm因为 getter 说,你也可以使用 id 而不是 name:

When a form element is indexed for named property retrieval, the user agent must run the following steps:

  1. Let candidates be a live RadioNodeList object containing all the listed elements whose form owner is the form element that have either an id attribute or a name attribute equal to name, [...]

现在回到你的问题:

As I'm writing this question, it sounds like something that I should just accept it and move on. But is there a reason not to use this way and just stick with getElementById or use the name attribute instead of the ID?

你不应该接受,除非你检查它是否 a) 标准和 b) 与你的目标浏览器兼容。由于它是标准的,您需要检查您的目标浏览器是否兼容。除此之外,这主要是个人喜好。

关于javascript - 为什么不需要 getElementById 来获取表单中的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21886512/

相关文章:

javascript - 如何在 javascript 中使用 .html() 将 html 作为文本插入?

javascript - 具有无限可选参数的 Backbone 路由

javascript - svg #文档加载事件

PHP:仅在 HTML 标记之外转义引号(正则表达式)

javascript - Textfield allowBlank/Focus 和 invalid-cls 问题

javascript - 我无法访问对象内数组中的所有元素

javascript - AJAX 不从 php 返回结果

php - 检查是否设置了 GET,然后发布与 PHP 变量连接的 HTML

django - 如何让 Django 表单显示 html 必需属性?

html - 绝对定位的元素的父元素绝对必须容纳子元素的高度