Javascript about looping checkbox

Javascript about looping checkbox

本文关键字:checkbox looping about Javascript      更新时间:2023-09-26

只是想问一下,为什么下面的代码无效(发现错误)

for(var i=1; i<10; i++)
{
  alert(window.document.FORM.checkbox[i].checked);
}

但是我可以执行以下操作,我只想循环在HTML中创建的复选框:

for(var i=1; i<10; i++)
{
  alert(window.document.FORM.checkbox1.checked);
}

你的两个陈述不一样;当我等于 1 时,你的陈述将被评估为

alert(window.document.FORM.checkbox[1].checked);

这与

alert(window.document.FORM.checkbox1.checked);

所以确实,要做到这一点,请使用Lee Taylor的解决方案,或者使用id重写整个方法,或者通过document.getElementsByTagName获取所有复选框,例如

var chks = document.getElementsByTagName("input");
for (var i=0, l=chks.length; i<l; i++) { 
  if ( chks[i].type === "checkbox" ) 
    alert(chks[i].checked);
}

呵呵,博瓦科

很奇怪,但你的代码对我有用。

for(var i=1; i<10; i++)
{
  alert(window.document.FORM.checkbox[i].checked);
}
<form name="FORM">
  <input type="checkbox" name="checkbox" checked="true" />
  <input type="checkbox" name="checkbox" checked="true" />
  <input type="checkbox" name="checkbox" />
  <input type="checkbox" name="checkbox" checked="true" />
  <input type="checkbox" name="checkbox" />
  <input type="checkbox" name="checkbox" />
  <input type="checkbox" name="checkbox" />
  <input type="checkbox" name="checkbox" checked="true" />
  <input type="checkbox" name="checkbox" />
  <input type="checkbox" name="checkbox" />
</form>