本文摘自PHP中文网,作者青灯夜游,侵删。
在html中,id属性和name属性都是提供标识符,表示HTML元素标签的。那么它们之间有什么区别?本篇文章就给大家简单比较一下id属性和name属性,介绍id属性和name属性之间的区别是什么,希望对大家有所帮助。
html中的id属性
我们使用id属性可以标识唯一的HTML元素,可以在在URL中用作锚引用(带#符号的URL),或者在css中用作ID选择器来设置该元素的样式。也可以在javascript中,使用getElementById(),通过id属性值来查找元素,在对元素进行操作。例:
1 2 | < p id = "p1" >测试文本!测试文本!</ p >
< p id = "p2" >测试文本!测试文本!</ p >
|

1 2 3 | <script>
document.getElementById( "p2" ).style.color= "red" ;
</script>
|

id属性是普遍兼容的,对任何元素都有效。且id属性的值是区分大小写的,每个id值都应该是唯一的。例:
1 2 3 4 | < div id = "demo" >
< div id = "a" >div标签,id值为a</ div >
< p id = "A" >p标签,id值为A</ p >
</ div >
|
1 2 | #a{ color : red ;}
#A{ color : pink;}
|
效果图:

html中的name属性
name属性同样是用来标识HTML元素的,但它不具有是唯一行,它的值可以重复使用,例:单选按钮
1 2 3 4 5 6 7 8 | < form action = "" method = "get" >
最喜欢水果?< br />< br />
< label >< input name = "Fruit" type = "radio" value = "" />苹果 </ label > < br />
< label >< input name = "Fruit" type = "radio" value = "" />桃子 </ label > < br />
< label >< input name = "Fruit" type = "radio" value = "" />香蕉 </ label > < br />
< label >< input name = "Fruit" type = "radio" value = "" />梨 </ label > < br />
< label >< input name = "Fruit" type = "radio" value = "" />其它 </ label > < br />
</ form >
|
效果图:

正如上例所示,name属性经常在表单中使用,用来提交信息;它仅对a, form, iframe, img, map, input, select, textarea等标签元素有效。
name属性可以在在javascript中,使用getElementsByName()来查找元素;但无法在CSS或URL中被引用。例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script type= "text/javascript" >
function getElements()
{
var x=document.getElementsByName( "myInput" );
alert(x.length);
}
</script>
<input name= "myInput" type= "text" size= "20" /><br />
<input name= "myInput" type= "text" size= "20" /><br />
<input name= "myInput" type= "text" size= "20" /><br />
<br />
<input type= "button" onclick= "getElements()" value= "名为 'myInput' 的元素有多少个?" />
|
效果图:

说明:
可以这样说,ID是一个人的身份证号码,而Name是这个人的名字。两者可以同时存在,共享相同的命名空间(两者的值可以相同)。
总结:以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。
以上就是html中id属性和name属性的区别是什么的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
Html设置图片透明
Html怎么设置背景图片全屏平铺?
Html标记是什么
Html文字怎么换行
Html legend标签怎么用
Html怎么设置文字的间距
Html标题在Html文档中为何重要
Html input标签怎么用
在Html中显示json数据的方法
Html文档的头部元素有哪些
更多相关阅读请进入《Html》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » html中id属性和name属性的区别是什么