HTML 输入 - 名称与 ID

发布于 2024-12-05 02:35:26 字数 102 浏览 8 评论 0 原文

使用 HTML 标签时,使用 nameid 属性有什么区别,特别是我发现它们有时名称相同?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

多情出卖 2024-12-12 02:35:26

在 HTML4.01 中:

Name 属性

Id 属性

  • 对除 << 之外的任何元素都有效。 html>、
  • 每个 ID 在页面中应该是唯一的如浏览器中呈现的那样,可能全部位于同一个文件中,也可能不全部位于同一个文件中
  • 可用作 URL 中的锚点引用
  • 在 CSS 中引用,或者带有 # 符号的 URL 中
  • 被引用在 JavaScript 中getElementById() 和 jQuery by $(#)
  • 与名称属性共享相同的名称空间
  • 必须包含至少一个字符
  • 必须以字母开头
  • 不得包含除字母、数字、下划线 (_)、破折号 (-)、冒号 (:) 或句点 (. )
  • 不区分

大小写(X)HTML5,一切都一样,除了:

Name 属性


  • 上无效
  • XHTML 表示它必须全部小写,但大多数浏览器不这样做t 遵循

Id 属性

  • 对任何元素有效
  • XHTML 表示它必须全部小写,但大多数浏览器不遵循

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

In HTML4.01:

Name Attribute

  • 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 JavaScript with getElementsByName()
  • Shares the same namespace as the id attribute
  • Must begin with a letter
  • According to specifications 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 name attribute are submitted to the server

Id Attribute

  • Valid on any element except <base>, <html>, <head>, <meta>, <param>, <script>, <style>, <title>
  • Each Id should be unique in the page as 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 JavaScript 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

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

Name Attribute

  • Not valid on <form> any more
  • XHTML says it must be all lowercase, but most browsers don't follow that

Id Attribute

  • Valid on any element
  • XHTML says it must be all lowercase, but most browsers don't follow that

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

倾城°AllureLove 2024-12-12 02:35:26

name 属性用于发布到例如 Web 服务器。 id 主要用于 CSS(和 JavaScript)。假设您有这样的设置:

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

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

$_POST["message_name"];

id 用于样式设置,如前所述,当您想要使用特定的 CSS 内容。

#message_id
{
    background-color: #cccccc;
}

当然,您可以对 idname 属性使用相同的面值。这两者不会互相干扰。

此外,name 可用于更多项目,例如当您使用单选按钮时。然后,名称将用于对单选按钮进行分组,因此您只能选择其中一个选项。

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

在这个非常具体的情况下,我可以进一步说明如何使用id,因为您可能需要一个带有单选按钮的标签。标签有一个 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>

The name attribute is used for posting to e.g. a web server. The id is primarily used for CSS (and JavaScript). Suppose you have this setup:

<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:

$_POST["message_name"];

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

#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.

Also, name can be used for more items, like when you are using radio buttons. Name is then used to group your radio buttons, 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 radio button. 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). An example can be found below

<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>
晨曦÷微暖 2024-12-12 02:35:26

ID 在页面 DOM 元素树中必须是唯一的

,因此每个控件都可以通过客户端(在浏览器页面内)

  • 加载的 JavaScript 脚本 页面
  • 通过其 id单独访问。页面上定义的

CSS 样式

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

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

在页面 DOM 内同一类型的多个控件之间共享(想想单选按钮),因此当数据获取 POSTed 到服务器,仅发送特定值。因此,当页面上有多个单选按钮时,即使有多个具有相同名称的相关单选按钮控件,也只会将所选单选按钮的发布回服务器。

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

当名称可以重复时 有时,

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

现在假设您有这种情况:

  • 您有一个包含相同类型的项目列表的视图,
  • 用户通常一次使用一项,因此他们只会输入一项单独的数据并将其发送到服务器

所以您的视图的模型(因为它显示一个列表)的类型为 IEnumerable,但您的服务器端仅接受 SomeType 类型的一项。

那么名称共享怎么样?

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

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

IDs must be unique

...within page DOM element tree so each control is individually accessible by its id on the client side (within browser page) by

  • JavaScript scripts loaded in the page
  • CSS styles defined on the page

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 seems that it works.

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 value gets posted back to server even though there are several related radio button controls with the same 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 pairs where name is the name of the input HTML control and value is its value as entered/selected by the user. This is always true for non-Ajax requests. In Ajax requests name-value pairs can be 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.

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.

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.

How about name sharing then?

Each item is wrapped within its own FORM element 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.

This particular scenario can be seen on my Creative stories mini-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.

谜泪 2024-12-12 02:35:26
  • name 标识表单字段*;因此它们可以由代表此类字段的多个可能值的控件(单选按钮、复选框)共享。它们将作为表单值的键提交。
  • id 标识 DOM 元素;因此它们可以被 CSS 或 JavaScript 定位。

* 名称用于识别本地锚点,但这已被弃用,“id”是当今的首选方式。

  • name identifies form fields*; 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.
  • id identifies DOM elements; so they can be targeted by CSS or JavaScript.

* name's are also used to identify local anchors, but this is deprecated and 'id' is a preferred way to do so nowadays.

为你拒绝所有暧昧 2024-12-12 02:35:26

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

id 也可以用作锚点。在过去, 用于此目的,但您也应该使用 id 作为锚点。 name 仅用于发布表单数据。

name is the name that is used when the value is passed (in the URL or in the posted data). id is used to uniquely identify the element for CSS styling and JavaScript.

The id can be used as an anchor too. In the old days, <a name was used for that, but you should use the id for anchors too. name is only to post form data.

辞别 2024-12-12 02:35:26

名称用于DOM<中的表单提交 /a>(文档对象模型)。

ID 用于 DOM 中 HTML 控件的唯一名称,尤其是 JavaScript 和 CSS。

name is used for form submission in the DOM (Document Object Model).

ID is used for a unique name of HTML controls in the DOM, especially for JavaScript and CSS.

护你周全 2024-12-12 02:35:26

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

id 用于在 JavaScript 或 CSS 中寻址字段或元素。

The name defines 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.

Whereas the id is used to address a field or element in JavaScript or CSS.

剩余の解释 2024-12-12 02:35:26

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

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

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

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

时光是把杀猪刀 2024-12-12 02:35:26

输入上的 name 属性由其父级 HTML

使用,以将该元素作为 HTTP 表单的成员包含在 POST 请求或 GET 请求中的查询字符串。

id 应该是唯一的,因为 JavaScript 应该使用它来选择 DOM 中的元素进行操作,并在 CSS 选择器中使用。

The name attribute on an input is used by its parent HTML <form>s to include that element as a member of the HTTP form in a POST request or the query string in a GET request.

The id should be unique as it should be used by JavaScript to select the element in the DOM for manipulation and used in CSS selectors.

风筝有风,海豚有海 2024-12-12 02:35:26

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

<!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>

在代码中,请注意,两个“name”属性相同,用于定义“male”或“female”之间的可选性,但“id”不等于来区分它们。

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.

℡寂寞咖啡 2024-12-12 02:35:26

添加一些对 W3C 文档的实际引用,权威地解释了表单上“name”属性的作用元素。 (无论如何,我来到这里的同时正在探索 Stripe.js 究竟如何实现与支付网关的安全交互Stripe。特别是,是什么导致表单输入元素提交回服务器,或阻止其提交?)

以下 W3C 文档是相关的:

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-0
https://www.w3.org/ TR/html5/forms.html#constructing-the-form-data-set 第 4.10.22.4 节构建表单数据集。

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

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

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

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

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

Adding some actual references to W3C documentation 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 the payment gateway Stripe. In particular, what causes a form input element to get submitted back to the server, or prevents it from being submitted?)

The following W3C documentation is relevant:

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

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

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.)

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 specifications, this applied to some deprecated uses of the name attribute (not on form elements). For example 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."

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.

凡尘雨 2024-12-12 02:35:26

使用相同名称的一个有趣的例子: checkbox 类型的 input 元素,如下所示:

<input id="fruit-1" type="checkbox" value="apple"  name="myfruit[]">
<input id="fruit-2" type="checkbox" value="orange" name="myfruit[]">

至少如果响应由 PHP 处理,如果您选中两个框,您的 POST 数据将显示:

$myfruit[0] == 'apple' && $myfruit[1] == 'orange'

我不知道其他服务器端语言是否会发生这种数组构造,或者 name 属性的值是否仅被视为字符串,并且它是构建基于 0 的数组的 PHP 语法的侥幸POST 响应中数据的顺序,就是:

myfruit[]       apple
myfruit[]       orange

不能用 ids 做那种把戏。 什么是 id 的有效值中的几个答案HTML 中的属性? 似乎引用了 HTML 4 的规范(尽管他们没有给出引用):

ID 和 NAME 令牌必须以字母 ([A-Za-z]) 开头,并且可以是
后跟任意数量的字母、数字 ([0-9])、连字符 (“-”)、
下划线(“_”)、冒号(“:”)和句点(“.”)。

因此,字符 [] 在 HTML4 中的 id 或名称中无效(它们在 HTML5 中是可以的)。但与 html 的许多东西一样,仅仅因为它无效并不意味着它不起作用或不是非常有用。

An interesting case of using the same name: input elements of type checkbox like this:

<input id="fruit-1" type="checkbox" value="apple"  name="myfruit[]">
<input id="fruit-2" type="checkbox" value="orange" name="myfruit[]">

At least if the response is processed by PHP, if you check both boxes, your POST data will show:

$myfruit[0] == 'apple' && $myfruit[1] == 'orange'

I don't know if that sort of array construction would happen with other server-side languages, or if the value of the name attribute is only treated as a string of characters, and it's a fluke of PHP syntax that a 0-based array gets built based on the order of the data in the POST response, which is just:

myfruit[]       apple
myfruit[]       orange

Can't do that kind of trick with ids. A couple of answers in What are valid values for the id attribute in HTML? appear to quote the spec for HTML 4 (though they don't give a citation):

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").

So the characters [ and ] are not valid in either ids or names in HTML4 (they would be okay in HTML5). But as with so many things html, just because it's not valid doesn't mean it won't work or isn't extremely useful.

夏见 2024-12-12 02:35:26

如果您使用 JavaScript/CSS,则必须使用控件的“id”来在其上应用任何 CSS/JavaScript 内容。

如果您使用 name,CSS 将不适用于该控件。例如,如果您使用附加到文本框的 JavaScript 日历,则必须使用文本控件的 id 为其分配 JavaScript 日历。

If you are using JavaScript/CSS, you must use the 'id' of a control to apply any CSS/JavaScript stuff on it.

If you use name, CSS won't work for that control. As an example, if you use a JavaScript calendar attached to a textbox, you must use the id of the text control to assign it the JavaScript calendar.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文