当使用HTML <input>标记时,使用名称和id属性之间的区别是什么,特别是我发现它们有时命名相同?
当前回答
名称标识表单字段*;因此,它们可以由表示该字段的多个可能值的控件(单选按钮、复选框)共享。它们将作为表单值的键提交。 id标识DOM元素;所以它们可以被CSS或JavaScript定位。
* name's也用于标识本地锚,但这是不赞成的,'id'是现在这样做的首选方式。
其他回答
id用于在JavaScript或CSS中唯一地标识一个元素。
该名称用于表单提交。当您提交表单时,只有带有名称的字段将被提交。
name用于在DOM(文档对象模型)中提交表单。
ID用于DOM中HTML控件的唯一名称,尤其是JavaScript和CSS控件。
name属性用于发布到例如web服务器。id主要用于CSS(和JavaScript)。假设你有这样的设置:
<input id="message_id" name="message_name" type="text" />
为了在发布表单时使用PHP获取该值,它将使用name属性,如下所示:
$_POST["message_name"];
如前所述,当您想使用特定的CSS内容时,id用于样式化。
#message_id
{
background-color: #cccccc;
}
当然,您可以对id和name属性使用相同的名称。这两者不会互相干扰。
此外,name可以用于更多的项目,比如当你使用单选按钮时。然后使用Name对单选按钮进行分组,因此只能选择其中一个选项。
<input id="button_1" type="radio" name="option" />
<input id="button_2" type="radio" name="option" />
在这个非常具体的例子中,我可以进一步说明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>
名称标识表单字段*;因此,它们可以由表示该字段的多个可能值的控件(单选按钮、复选框)共享。它们将作为表单值的键提交。 id标识DOM元素;所以它们可以被CSS或JavaScript定位。
* name's也用于标识本地锚,但这是不赞成的,'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是标准的时候写的,许多浏览器和功能都与今天不同。
推荐文章
- 使伸缩项目正确浮动
- 形式内联内的形式水平在twitter bootstrap?
- 自定义元素在HTML5中有效吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 在网页上用鼠标模拟震颤(例如帕金森病)?
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何改变文本区域的边框颜色:焦点
- 我如何设置背景颜色为文本的宽度,而不是整个元素的宽度,使用CSS?
- 如何删除和清除所有的本地存储数据
- 强制打开“另存为…”弹出打开文本链接点击PDF在HTML
- 如何修改标签文本?
- 在HTML中还有其他有用的空格码吗,比如半空格的 , em-spaces, en-spaces等等?
- 输入触发器按钮单击