关于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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值