我在 for 循环中的这段代码中得到以下错误但是当我给 iput+=checkedBoxes[1].id staticaly 意味着它正在工作请帮助并警告 for 循环正在使用 s
错误:未捕获的类型错误:无法在 saveSign 读取未定义的属性“id”
function saveSign(){
alert('asd')
var iput =[];
var checkedBoxes = document.querySelectorAll('input[type=checkbox]');
for (var s=1;s<=checkedBoxes.length;s++){
iput+=checkedBoxes[s].id
}
console.log(iput)
}
问题与您的 for 循环的循环计数器有关。它从 1 开始,跳过第一个数组元素,然后继续到长度,即数组中的索引不存在任何元素。您可以使用 for-of 循环或forEach
回调完全避免循环计数器。
我还注意到您+=
在数组 ( iput
)上使用了运算符。要将元素附加到数组,请使用push
方法。如果需要字符串,请设置iput
为空字符串 ( ''
) 并保留+=
.
最后,您省略了几个分号。由于自动分号插入的缺陷,只要有可能就使用它们来避免意外行为会更容易。
使用普通的 for 循环:
function saveSign() {
const iput = [];
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
for(let i = 0; i < checkedBoxes.length; i++) {
iput.push(checkedBoxes[i].id);
}
console.log(iput);
}
使用for-of循环:
function saveSign() {
const iput = [];
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
for(const checkedBox of checkedBoxes) {
iput.push(checkedBox.id);
}
console.log(iput);
}
使用forEach
回调:
function saveSign() {
const iput = [];
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
checkedBoxes.forEach((checkedBox) => {
iput.push(checkedBox);
});
console.log(iput);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句