当使用HTML <input>标记时,使用名称和id属性之间的区别是什么,特别是我发现它们有时命名相同?


当前回答

名称标识表单字段*;因此,它们可以由表示该字段的多个可能值的控件(单选按钮、复选框)共享。它们将作为表单值的键提交。 id标识DOM元素;所以它们可以被CSS或JavaScript定位。

* name's也用于标识本地锚,但这是不赞成的,'id'是现在这样做的首选方式。

其他回答

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

id也可以用作锚。在过去,它使用<a名称,但您也应该对锚使用id。名称仅用于发布表单数据。

在HTML4.01:

名称属性

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属性

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

在(X)HTML5中,一切都是一样的,除了:

名称属性

在<form>上无效 XHTML规定必须全部小写,但大多数浏览器不遵守这一规定

Id属性

对任何元素都有效 XHTML规定必须全部小写,但大多数浏览器不遵守这一规定

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

name用于在DOM(文档对象模型)中提交表单。

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

名称标识表单字段*;因此,它们可以由表示该字段的多个可能值的控件(单选按钮、复选框)共享。它们将作为表单值的键提交。 id标识DOM元素;所以它们可以被CSS或JavaScript定位。

* name's也用于标识本地锚,但这是不赞成的,'id'是现在这样做的首选方式。

如果你使用JavaScript/CSS,你必须使用控件的“id”来应用任何CSS/JavaScript的东西。

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