`
hyshucom
  • 浏览: 802817 次
文章分类
社区版块
存档分类
最新评论

关于document.getElementsByName的奇怪问题

 
阅读更多

先看以下代码:
<html>
<head>
<script language="JavaScript">
function init()
{
if(document.all('items')==null){
alert('items is null');
}else{
alert('items is not null ,is :'+document.all('items'));
}
//现在document.all('items')仍然为空
var v_items = document.getElementsByName('items');
if(v_items==null){
alert('v_items is null');
}else{
alert('v_items is not null , is : '+v_items);
}
if(document.all('items')==null){
alert('items is null');
}else{
alert('items is not null ,is :'+document.all('items'));
}
//现在document.all('items')为什么不为空了呢?
}
</script>
</head>
<body onLoad="init();">

</body>
</html>

为什么在调用document.getElementsByName('items');之前document.all('items')等于null,而在调用之后document.all('items')就不为空了呢?

回复:

document.getElementsByName('items');

不管'items'元素存在否,都会创建/返回name='items'的元素集合(type=[object]),如果'items'元素不存在集合--[object].length=0,或者'items'元素存在N个[object].length=N

document.all('items')是对name='items'的元素集合的引用,如果存在name='items'的元素,系统会自动创建

因此,
第一段,name='items'的元素不存在,系统不会创建name='items'的元素集合,document.all('items')得到null
第二段,document.getElementsByName('items')创建/返回name='items'的元素集合(name='items'的元素不存在,此时集合长度=0)
第三段document.all('items')直接引用name='items'的元素集合(已经存在),得到[object]
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics