getElementsByName 和 getElementById 方法在IE 和Google FF浏览器区别

编程技术  /  houtizong 发布于 3年前   108
今天在测试的时候发现getElementsByName在IE中好使,在google中不好使,后面发现传入的值是节点的ID,后面查询资料发现如下:
对于ID & Name 按最经典的解释的:“ID 就如同我们的身份证,Name就如同我们的名字”,也就是说,在一个html文档中ID是唯一的,但是Name是可以重复的,就象我们的人名可以重复但是身份证确实全中国唯一的(PS:据说有重复的^_^)
但是对于document.getElementsByName 与document.getElementById 这个两个方法,IE中是并没有严格区分 ID 与 Name 的,比如:
<script type="text/javascript">
function useGetElementsByNameWithId(id) {
var eles = document.getElementsByName('ID_A');
var msg = '使用 getElementsByName 传入 ID:得到:'
if(eles.length > 0) {
msg += " Name " + eles[0].id;
}
alert(msg);
}
function usegetElementByIdWithName(name) {
var ele = document.getElementById(name);
var msg = '使用 getElementById 传入 Name 得到:';
if(ele) {
msg += " ID " + ele.id;
}
alert(msg);
}
</script><input id="ID_A" name="Name_A" type="button" value="使用 getElementsByName 传入 ID" onclick="useGetElementsByNameWithId(this.id)" />
<input id="ID_B" name="Name_B" type="button" value="使用 getElementsByName 传入 Name" onclick="usegetElementByIdWithName(this.name)" />IE中通过 getId 传入 name 同样可以访问到目标元素,而通过 getName 传入 Id 也可以访问到目标元素。
MSDN中对两个方法的解释:
getElementById Method
--------------------------------------------------------------------------------
Returns a reference to the first object with the specified value of the ID attribute.
Remarks
When you use the getElementsByName method, all elements in the document that have the specified NAME or ID attribute value are returned.
Elements that support both the NAME and the ID attribute are included in the collection returned by the getElementsByName method, but not elements with a NAME expando.
MSDN确实对 getElementsByName 方法做了说明:“具有指定 Name 或者 ID 属性的元素都会返回”,但是
getElementById 方法却没有说明,然而内部实现同 getElementsByName 是一样的。
而对于Google,看来更忠实W3C标准,上面的测试代码是没有办法返回目标元素的。

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客