html 中真的需要 name 属性吗? [英] was the name attribute really needed in html?
问题描述
如果 HTML 表单中的 name 属性的目的只是引用元素,例如 input,为什么我们不能简单地使用 id 或 class 属性?创建 name 属性背后是否有一些不那么明显的推理.
.....html名称:<input type="text" name="fullname"><br>.....
name
、id
和 class
具有根本不同的用途.
name
用于表单元素名称,不需要唯一(实际上,有时您需要重复使用相同的name
).id
顾名思义,是一个元素的标识符,并且在整个文档中必须是唯一的.class
主要用于表示(虽然有时也用于连接客户端 UI),并且包含元素的类的列表,而不仅仅是一个单班.如果您使用class
进行表单字段识别,您会使用哪几个类?
在多个字段上使用相同name
的方法:
您可以在不同形式中使用相同的
name
,而不会产生任何冲突.对于应该组合在一起的单选按钮,您在表单中使用相同的
name
.您可以在一个表单中为多种其他类型的元素使用相同的
name
,这些元素的值应该全部发送到服务器.
相反,id
必须是唯一的 —不仅在表单内,而且在整个文档内.
#3 可能需要一个例子来清楚起见.假设您有:
如果用户在这三个文本字段中填写a
、b
和c
并发送表单,这就是查询字符串:
注意 foo
是重复的.接收资源可以访问所有这三个值.(也许您要列出帖子的标签,或者您所有孩子的名字,或者...)
If the purpose of the name attribute in HTML forms only to reference the element such as input, why couldn't we have simply used id or class attributes? Was there some not so obvious reasoning behind creating the name attribute.
.....html
Name: <input type="text" name="fullname"><br>
.....
name
, id
, and class
have fundamentally different purposes.
name
is for form element names and is not required to be unique (in fact, sometimes you need to reuse the samename
).id
is, as the name indicates, an identifier for an element and must be unique in the document as a whole.class
is primarily for presentation (although it sometimes used for hooking up client-side UI as well) and contains a list of classes for the element, not just a single class. If you usedclass
for form field identification, which of the possibly-several classes would you use?
Ways you might use the same name
on more than one field:
You can use the same
name
in different forms without there being any conflict.You use the same
name
within a form for radio buttons that should be grouped together.You can use the same
name
within a form for multiple other kinds of elements whose values should all be sent to the server.
In contrast, id
must be unique — not only within the form, but within the entire document.
#3 might need an example for clarity. Suppose you have:
<form action="example" method="get">
<input type="text" name="foo">
<input type="text" name="foo">
<input type="text" name="foo">
<input type="submit" value="Send">
</form>
If the user fills in a
, b
, and c
in those three text fields and sends the form, this is the query string:
?foo=a&foo=b&foo=c
Notice that foo
was repeated. The receiving resource can access all three of those values. (Perhaps you're listing tags for a post, or all of your children's names, or...)
这篇关于html 中真的需要 name 属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!