HTML 输入 - 名称与 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7470268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:41:53  来源:igfitidea点击:

HTML input - name vs. id

htmlhtml-input

提问by Simplicity

When using the HTML <input>tag, what is the difference between the use of the nameand idattributes especially that I found that they are sometimes named the same?

使用 HTML<input>标签时,使用nameid属性有什么区别,尤其是我发现它们有时命名相同?

回答by Kumar Akarsh

In HTML4.01:

在 HTML4.01 中:

NameAttribute

名称属性

  • Valid only on <a>, <form>, <iframe>, <img>, <map>, <input>, <select>, <textarea>
  • Name does not have to be unique, and can be used to group elements together such as radio buttons & checkboxes
  • Can not be referenced in URL, although as JavaScript and PHP can see the URL there are workarounds
  • Is referenced in JS with getElementsByName()
  • Shares the same namespace as the idattribute
  • Must begin with a letter
  • According to specs is case sensitive, but most modern browsers don't seem to follow this
  • Used on form elements to submit information. Only input tags with a nameattribute are submitted to the server
  • 仅在<a>, <form>, <iframe>, <img>, <map>, <input>, <select>, 上有效<textarea>
  • 名称不必是唯一的,可用于将元素组合在一起,例如单选按钮和复选框
  • 无法在 URL 中引用,尽管 JavaScript 和 PHP 可以看到 URL 有一些解决方法
  • 在 JS 中被引用 getElementsByName()
  • id属性共享相同的命名空间
  • 必须以字母开头
  • 根据规范区分大小写,但大多数现代浏览器似乎并不遵循这一点
  • 用于表单元素以提交信息。只有带有name属性的输入标签才会提交给服务器

IdAttribute

id属性

  • Valid on any element except <base>, <html>, <head>, <meta>, <param>, <script>, <style>, <title>
  • Each Id should be unique in the pageas rendered in the browser, which may or may not be all in the same file
  • Can be used as anchor reference in URL
  • Is referenced in CSS or URL with #sign
  • Is referenced in JS with getElementById(), and jQuery by $(#<id>)
  • Shares same name space as name attribute
  • Must contain at least one character
  • Must begin with a letter
  • Must not contain anything other than letters, numbers, underscores (_), dashes (-), colons (:), or periods (.)
  • Is case insensitive
  • 对任何元素有效,除了<base>, <html>, <head>, <meta>, <param>, <script>, <style>,<title>
  • 每个 Id在浏览器中呈现的页面中都应该是唯一的,这些 ID可能会也可能不会都在同一个文件中
  • 可以用作 URL 中的锚引用
  • 在 CSS 或 URL 中引用带#符号
  • 在 JS 中通过getElementById(), 和 jQuery引用$(#<id>)
  • 与 name 属性共享相同的命名空间
  • 必须至少包含一个字符
  • 必须以字母开头
  • 不得包含除字母、数字、下划线 ( _)、破折号 ( -)、冒号 ( :) 或句点 ( .) 以外的任何内容
  • 不区分大小写

In (X)HTML5, everything is the same except:

在 (X)HTML5 中,除了:

NameAttribute

名称属性

  • Not valid on <form>anymore
  • XHTML says it must be all lowercase, but most browsers don't follow that
  • 对无效<form>
  • XHTML 说它必须全部小写,但大多数浏览器不遵循这一点

IdAttribute

id属性

  • Valid on any element
  • XHTML says it must be all lowercase, but most browsers don't follow that
  • 对任何元素有效
  • XHTML 说它必须全部小写,但大多数浏览器不遵循这一点

This question was written when HTML4.01 was the norm, and many browsers and features were different from today.

这个问题是在 HTML4.01 成为常态的时候写的,许多浏览器和功能与今天不同。

回答by Michiel Standaert

the name attribute is used for posting to e.g. a webserver. The id is primarily used for css (and javascript). Suppose you have this setup:

name 属性用于发布到例如网络服务器。id 主要用于 css(和 javascript)。假设你有这样的设置:

<input id="message_id" name="message_name" type="text" />

in order to get the value with PHP when posting your form, it will use the name-attribute, like this:

为了在发布表单时使用 PHP 获取值,它将使用名称属性,如下所示:

$_POST["message_name"];

The id is used for styling, as said before, for when you want to use specific css.

id 用于样式,如前所述,当您想使用特定的 css 时。

#message_id
{
    background-color: #cccccc;
}

Of course, you can use the same denomination for your id and name-attribute. These two will not interfere with each other.

当然,您可以为您的 id 和 name-attribute 使用相同的面额。这两者不会互相干扰。

also, name can be used for more items, like when you are using radiobuttons. Name is then used to group your radiobuttons, so you can only select one of those options.

此外,名称可用于更多项目,例如当您使用单选按钮时。然后使用名称对您的单选按钮进行分组,因此您只能选择这些选项之一。

<input id="button_1" type="radio" name="option" />
<input id="button_2" type="radio" name="option" />

And in this very specific case, I can further say how id is used, because you will probably want a label with your radiobutton. Label has a for-attribute, which uses the id of your input to link this label to your input (when you click the label, the button is checked). Example can be found below

在这种非常具体的情况下,我可以进一步说明 id 的使用方式,因为您可能需要带有单选按钮的标签。Label 有一个 for 属性,它使用您输入的 id 将此标签链接到您的输入(当您单击标签时,该按钮被选中)。示例可以在下面找到

<input id="button_1" type="radio" name="option" /><label for="button_1">Text for button 1</label>
<input id="button_2" type="radio" name="option" /><label for="button_2">Text for button 2</label>

回答by Robert Koritnik

IDs must be unique

ID 必须是唯一的

...within page DOM element tree so each control is individually accessibleby its idon the client side (within browser page) by

页面的DOM元素树中...所以每个控制是单独访问id通过在客户端(浏览器内页)

  • Javascript scripts loaded in the page
  • CSS styles defined on the page
  • 页面中加载的 Javascript 脚本
  • 页面上定义的 CSS 样式

Having non-unique IDs on your page will still render your page, but it certainly won't be valid. Browsers are quite forgiving when parsing invalid HTML. but don't do that just because it seemsthat it works.

在您的页面上使用非唯一 ID 仍会呈现您的页面,但它肯定是无效的。浏览器在解析无效的 HTML 时非常宽容。但不要仅仅因为它看起来有效就这样做。

Names are quite often unique but can be shared

名称通常是唯一的,但可以共享

...within page DOM between several controls of the same type (think of radio buttons) so when data gets POSTed to server only a particular value gets sent. So when you have several radio buttons on your page, only the selected one's valuegets posted back to server even though there are several related radio button controls with the same name.

...在相同类型的多个控件之间的页面 DOM 内(想想单选按钮),因此当数据被 POST 到服务器时,只会发送一个特定的值。因此,当您的页面上有多个单选按钮时,value即使有多个相关的单选按钮控件具有相同的name.

Addendum to sending data to server: When data gets sent to server (usually by means of HTTP POST request) all data gets sent as name-value pairswhere nameis the nameof the input HTML control and valueis its valueas entered/selected by the user. This is always true for non-Ajax requests. In Ajax requests name-value pairs canbe independent of HTML input controls on the page, because developers can send whatever they want to the server. Quite often values are also read from input controls, but I'm just trying to say that this is not necessarily the case.

将数据发送到服务器的附录:当数据发送到服务器时(通常通过 HTTP POST 请求),所有数据都以名称-值对的形式发送,其中名称name输入 HTML 控件的名称,是其value输入/选择的用户。对于非 Ajax 请求,这总是正确的。在 Ajax 请求中,名称-值对可以独立于页面上的 HTML 输入控件,因为开发人员可以向服务器发送他们想要的任何内容。值也经常从输入控件中读取,但我只是想说情况并非一定如此。

When names can be duplicated

何时可以重复名称

It may sometimes be beneficial that names are shared between controls of any form input type. But when? You didn't state what your server platform may be, but if you used something like Asp.net MVC you get the benefit of automatic data validation (client and server) and also binding sent data to strong types. That means that those names have to match type property names.

在任何表单输入类型的控件之间共享名称有时可能是有益的。但当?您没有说明您的服务器平台可能是什么,但是如果您使用类似 Asp.net MVC 的东西,您将获得自动数据验证(客户端和服务器)的好处,并将发送的数据绑定到强类型。这意味着这些名称必须与类型属性名称匹配。

Now suppose you have this scenario:

现在假设你有这个场景:

  • you have a view with a list of items of the same type
  • user usually works with one item at a time, so they will only enter data with one item alone and send it to server
  • 您有一个包含相同类型项目列表的视图
  • 用户通常一次处理一项,因此他们只会单独输入一项数据并将其发送到服务器

So your view's model (since it displays a list) is of type IEnumerable<SomeType>but your server side only accepts one single item of type SomeType.

所以你的视图模型(因为它显示一个列表)是 typeIEnumerable<SomeType>但你的服务器端只接受一个 type 的项目SomeType

How about name sharing then?

那么名称共享呢?

Each item is wrapped within its own FORMelement and input elements within it have the same names so when data gets to the server (from any element) it gets correctly bound to the string type expected by the controller action.

每个项目都包含在它自己的FORM元素中,并且其中的输入元素具有相同的名称,因此当数据到达服务器(从任何元素)时,它会正确绑定到控制器操作所需的字符串类型。

This particular scenario can be seen on my Creative storiesmini-site. You won't understand the language, but you can check out those multiple forms and shared names. Never mind that IDs are also duplicated (which is a rule violation) but that could be solved. It just doesn't matter in this case.

这个特殊的场景可以在我的创意故事迷你网站上看到。您不会理解该语言,但您可以查看这些多个表单和共享名称。不要介意IDs 也重复(这是违反规则的),但这可以解决。在这种情况下,这无关紧要。

回答by Javarome

  • nameidentifies formfields* ; so they can be shared by controls that stand to represent multiple possibles values for such a field (radio buttons, checkboxes). They will be submitted as keys for form values.
  • ididentifies DOMelements ; so they can be targeted by CSS or Javascript.
  • name标识表单域*;因此它们可以由代表此类字段的多个可能值的控件共享(单选按钮、复选框)。它们将作为表单值的键提交。
  • id标识DOM元素;所以它们可以被 CSS 或 Javascript 定位。

* names also used toidentify local anchors, but this is deprecated and 'id' is a preferred way to do so nowadays.

* 名称也用于标识本地锚点,但现在已弃用,'id' 是一种首选方式。

回答by GolezTrol

nameis the name that is used when the value is passed (in the url or in the posted data). idis used to uniquelyidentify the element for CSS styling and JavaScript.

name是传递值时使用的名称(在 url 中或在发布的数据中)。id用于唯一标识 CSS 样式和 JavaScript 的元素。

The idcan be used as an anchor too. In the old days, <a namewas used for that, but you should use the idfor anchors too. nameis only to post form data.

id可作为锚了。在过去,<a name用于那个,但你也应该使用idfor 锚点。name只是发布表单数据。

回答by Anjan Kant

nameis used for form submissionin DOM(Document Object Model).

名称被用于表单提交DOM(文档对象模型)。

IDis used to unique nameof html controls in DOM specially for Javascript& CSS

ID用于DOM 中 html 控件的唯一名称,专门用于Javascript& CSS

回答by Matschie

The name definies what the name of the attribute will be as soon as the form is submitted. So if you want to read this attribute later you will find it under the "name" in the POST or GET Request.

该名称定义了提交表单后属性的名称。因此,如果您想稍后阅读此属性,您将在 POST 或 GET 请求中的“名称”下找到它。

Whereas the id is used to adress a field or element in javascript or css.

而 id 用于寻址 javascript 或 css 中的字段或元素。

回答by Viyaan Jhiingade

The id is used to uniquely identify an element in JavaScript or CSS.

id 用于唯一标识 JavaScript 或 CSS 中的元素。

The name is used in form submission. When you submit a form only the fields with a name will be submitted.

该名称用于表单提交。当您提交表单时,只会提交带有名称的字段。

回答by Clemencio Morales Lucas

I hope you can find the following brief example helpful:

我希望以下简短示例对您有所帮助:

<!DOCTYPE html>
<html>
<head>
  <script>
    function checkGender(){
      if(document.getElementById('male').checked) {
         alert("Selected gender: "+document.getElementById('male').value)
      }else if(document.getElementById('female').checked) {
         alert("Selected gender: "+document.getElementById('female').value)
      }
      else{
         alert("Please choose your gender")
      }
    }
  </script>
</head>
<body>
<h1>Select your gender:</h1>

<form>
  <input type="radio" id="male" name="gender" value="male">Male<br>
  <input type="radio" id="female" name="gender" value="female">Female<br>
  <button onclick="checkGender()">Check gender</button> 
</form> 
</body>
</html>

In the code, note that both 'name' attributes are the same to define optionality between 'male' or 'female', but the 'id's are not equals to differentiate them.

在代码中,请注意,两个 'name' 属性是相同的,用于定义 'male' 或 'female' 之间的可选性,但 'id's are not equals 来区分它们。

回答by gwideman

Adding some actual references to W3 docs that authoritatively explain the role of the 'name' attribute on form elements. (For what it's worth, I arrived here while exploring exactly how Stripe.js works to implement safe interaction with payment gateway Stripe. In particular, what causes a form input element to get submitted back to the server, or prevents it from being submitted?)

添加一些对 W3 文档的实际引用,这些文档权威地解释了“名称”属性在表单元素上的作用。(对于它的价值,我来到这里是为了探索 Stripe.js 如何工作以实现与支付网关 Stripe 的安全交互。特别是,是什么导致表单输入元素被提交回服务器,或阻止它被提交? )

The following W3 docs are relevent:

以下 W3 文档是相关的:

HTML 4: https://www.w3.org/TR/html401/interact/forms.html#control-nameSection 17.2 Controls

HTML 4:https: //www.w3.org/TR/html401/interact/forms.html#control-name第 17.2 节控件

HTML 5: https://www.w3.org/TR/html5/forms.html#form-submission-0and https://www.w3.org/TR/html5/forms.html#constructing-the-form-data-setSection 4.10.22.4 Constructing the form data set.

HTML 5:https: //www.w3.org/TR/html5/forms.html#form-submission-0https://www.w3.org/TR/html5/forms.html#constructing-the-form -data-set第 4.10.22.4 节构建表单数据集。

As explained therein, an input element will be submitted by the browser if and only if it has a valid 'name' attribute.

正如其中所解释的,当且仅当输入元素具有有效的“名称”属性时,浏览器才会提交该元素。

As others have noted, the 'id' attribute uniquely identifies DOM elements, but is not involved in normal form submission. (Though 'id' or other attributes can of course be used by javascript to obtain form values, which javascript could then use for AJAX submissions and so on.)

正如其他人所指出的,“id”属性唯一标识 DOM 元素,但不涉及正常的表单提交。(尽管 'id' 或其他属性当然可以被 javascript 使用来获取表单值,然后 javascript 可以将其用于 AJAX 提交等。)

One oddity regarding previous answers/commenters concern about id's values and name's values being in the same namespace. So far as I can tell from the specs, this applied to some deprecated uses of the name attribute (not on form elements). For example https://www.w3.org/TR/html5/obsolete.html:

关于以前的答案/评论者的一个奇怪之处在于 id 的值和 name 的值位于同一命名空间中。据我从规范中可以看出,这适用于 name 属性的一些已弃用的用途(不在表单元素上)。例如https://www.w3.org/TR/html5/obsolete.html

"Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's home subtree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's home subtree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragment identifiers in URLs. The id attribute should be used instead."

“作者不应在元素上指定 name 属性。如果该属性存在,则其值不得为空字符串,并且不得等于元素主子树中除元素自己的 ID 之外的任何 ID 的值,如果有,也不等于元素主子树中元素的任何其他名称属性的值。如果存在此属性并且元素具有 ID,则该属性的值必须等于元素的 ID。在该语言的早期版本中,此属性旨在为 URL 中的片段标识符指定可能的目标。应该改用 id 属性。”

Clearly in this special case there's some overlap between id and name values for 'a' tags. But this seems to be a peculiarity of processing for fragment ids, not due to general sharing of namespace of ids and names.

很明显,在这种特殊情况下,“a”标签的 id 和 name 值之间存在一些重叠。但这似乎是处理片段 id 的一个特殊性,而不是由于 id 和名称的命名空间的一般共享。