当利用for loop为若干个radio input元素添加eventlistener的时候并未生效,错误提示为:Uncaught TypeError: value.addEventListener is not a function。请问这是为什么?
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<div class="size_radio1">
<input type="radio" name="radio1" id="50" data-add="100">50cm
<input type="radio" name="radio1" id="75" data-add="200">75cm
<input type="radio" name="radio1" id="100" data-add="300">100cm
<input type="radio" name="radio1" id="150" data-add="400">150cm
<input type="radio" name="radio1" id="225" data-add="500">225cm
div>
body>
<script>
let value1 = document.querySelector(".size_radio1");
let cm_values = value1.querySelectorAll("input");
function cm_se(){
console.log("Yay!");
}
for (let value in cm_values){
value.addEventListener("click",cm_se);
}
script>
html>
for...in 循环遍历的是数组的索引而不是元素本身。因此,在循环中使用 value 作为变量时,其实是当前元素的索引值而不是输入框元素本身。
由于索引并没有 addEventListener 方法,所以会抛出 "Uncaught TypeError: value.addEventListener is not a function" 错误。
要解决这个问题,可以使用 for...of 循环来遍历元素本身
for(let value of cm_values){
value.addEventListener("click",cm_se);
}
使用 for...of 循环后,变量 value 将代表当前输入框元素而不是索引值
该回答引用GPTᴼᴾᴱᴺᴬᴵ
问题在于你使用了 for...in 循环,但是 cm_values 不是一个普通的数组,而是一个类数组对象。for...in 循环会遍历对象的所有可枚举属性,包括数组的原型链上的属性和非数字类型的属性,这样可能会导致一些错误。
应该使用 for...of 循环来遍历节点列表,例如:
let value1 = document.querySelector(".size_radio1");
let cm_values = value1.querySelectorAll("input");
function cm_se(){
console.log("Yay!");
}
for (let value of cm_values){
value.addEventListener("click",cm_se);
}
这样就能够为每个 radio input 元素添加 click 事件监听器了。