最佳实践:通过 HTML id 或 name 属性访问表单元素? [英] Best Practice: Access form elements by HTML id or name attribute?

查看:23
本文介绍了最佳实践:通过 HTML id 或 name 属性访问表单元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何经验丰富的 JavaScript 开发人员都知道,有很多(太多)方法可以做同样的事情.例如,假设您有一个文本字段,如下所示:

As any seasoned JavaScript developer knows, there are many (too many) ways to do the same thing. For example, say you have a text field as follows:

<form name="myForm">  
    <input type="text" name="foo" id="foo" />

在 JavaScript 中有很多方法可以访问它:

There are many way to access this in JavaScript:

[1]  document.forms[0].elements[0];
[2]  document.myForm.foo;
[3]  document.getElementById('foo');
[4]  document.getElementById('myForm').foo;
     ... and so on ...

方法 [1] 和 [3] 在 Mozilla Gecko 文档中有详细记录,但都不是理想的方法.[1] 太笼统而没有用,[3] 需要一个 id 和一个名称(假设您将数据发布到服务器端语言).理想情况下,最好只有一个 id 属性或一个 name 属性(同时拥有两个属性有些是多余的,特别是如果 id 对于任何 css 都不是必需的,并且会增加拼写错误的可能性等).

Methods [1] and [3] are well documented in the Mozilla Gecko documentation, but neither are ideal. [1] is just too general to be useful and [3] requires both an id and a name (assuming you will be posting the data to a server side language). Ideally, it would be best to have only an id attribute or a name attribute (having both is somewhat redundant, especially if the id isn't necessary for any css, and increases the likelihood of typos, etc).

[2] 似乎是最直观的,而且似乎被广泛使用,但我没有在 Gecko 文档中看到它被引用,我担心向前兼容性和跨浏览器兼容性(当然我希望尽可能符合标准).

[2] seems to be the most intuitive and it seems to be widely used, but I haven't seen it referenced in the Gecko documentation and I'm worried about both forwards compatibility and cross browser compatiblity (and of course I want to be as standards compliant as possible).

那么这里的最佳实践是什么?谁能指出 DOM 文档或 W3C 规范中可以解决此问题的内容?

So what's best practice here? Can anyone point to something in the DOM documentation or W3C specification that could resolve this?

请注意,我对非库解决方案(jQuery/Prototype)特别感兴趣.

Note I am specifically interested in a non-library solution (jQuery/Prototype).

推荐答案

只给你的表单一个 id,给你的输入一个 name :

Give your form an id only, and your input a name only:

<form id="myform">
  <input type="text" name="foo">

那么访问输入元素最符合标准且问题最少的方法是通过:

Then the most standards-compliant and least problematic way to access your input element is via:

document.getElementById("myform").elements["foo"]

使用 .elements["foo"] 而不是 .foo 更可取,因为后者可能返回名为foo"的表单属性而不是 HTML元素!

using .elements["foo"] instead of just .foo is preferable because the latter might return a property of the form named "foo" rather than a HTML element!

这篇关于最佳实践:通过 HTML id 或 name 属性访问表单元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆