当使用HTML <input>标记时,使用名称和id属性之间的区别是什么,特别是我发现它们有时命名相同?
当前回答
名称定义了表单提交后属性的名称。因此,如果您稍后想要读取此属性,您将在POST或GET请求中的“name”下找到它。
而在JavaScript或CSS中,id用于寻址字段或元素。
其他回答
如果你使用JavaScript/CSS,你必须使用控件的“id”来应用任何CSS/JavaScript的东西。
如果使用name, CSS将不能用于该控件。例如,如果使用JavaScript日历附加到文本框,则必须使用文本控件的id为其分配JavaScript日历。
我希望下面的例子对你有帮助:
<!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'不等于以区分它们。
添加一些对W3C文档的实际引用,以权威地解释'name'属性在表单元素上的作用。(不管怎样,我是在探索Stripe.js如何与支付网关Stripe实现安全交互时来到这里的。具体来说,是什么导致表单输入元素被提交回服务器,或者阻止它被提交?)
以下W3C文档是相关的:
Section 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构造表单数据集。
如文中所述,当且仅当输入元素具有有效的'name'属性时,浏览器才会提交输入元素。
正如其他人所注意到的,'id'属性唯一地标识DOM元素,但不涉及正常的表单提交。(虽然JavaScript当然可以使用'id'或其他属性来获取表单值,然后JavaScript可以将其用于Ajax提交等等。)
关于前面的回答/评论,一个奇怪的问题是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."
显然,在这个特殊情况下,'a'标记的id值和name值之间有一些重叠。但这似乎是片段id处理的一种特性,而不是由于id和名称的命名空间普遍共享。
id用于在JavaScript或CSS中唯一地标识一个元素。
该名称用于表单提交。当您提交表单时,只有带有名称的字段将被提交。
name是传递值时使用的名称(在URL中或在发布的数据中)。id用于唯一标识CSS样式和JavaScript元素。
id也可以用作锚。在过去,它使用<a名称,但您也应该对锚使用id。名称仅用于发布表单数据。