通过循环为一个数组里面的每个标签元素注册事件的时候,在事件函数里面通过数组下标为每个标签设置属性的时候会报错——解决办法

本文介绍了一个关于JavaScript点击事件处理的常见错误,即在循环中使用变量i作为索引时,由于作用域问题导致的错误,并提供了解决方案,即将radios[i]替换为this,确保点击事件正确绑定。

例子:

<style>
    /* input属于行内替换元素 */
    input{
      width: 100px;
      height: 100px;
      background-color: red;
      color: white;
    }
</style>


<input type="button"  name="buttons" value="第一个">
<input type="button"  name="buttons" value="第二个">
<input type="button"  name="buttons" value="第三个">
<input type="button"  name="buttons" value="第四个">
<input type="button"  name="buttons" value="第五个">
<input type="button"  name="buttons" value="第六个">

<script>

  //获取到所有input标签的一个数组
  var radios = document.getElementsByName("buttons");

  //通过循环为每个标签注册点击事件
  for (var i = 0; i < radios.length; i++) {

    radios.item(i).onclick = function () {

      //在点击某个按钮之前,需要把所得按钮的背景颜色重置
      for (var j = 0; j < radios.length; j++) {
          radios[j].style.backgroundColor = "red"
      }

      //设置点击的按钮时,背景颜色变化
      radios[i].style.backgroundColor = "green"
    }
  }
</script>


解释:在这个案例中,我们打算实现鼠标点击那个按钮,那么那个按钮的颜色变成绿色,其他的按钮全部是红色,但是当我们随机点击一个按钮,没有出现效果,反而报错。

报错:Uncaught TypeError: Cannot read property 'style' of undefined at HTMLInputElement.radios.item.onclick (01.html:41)

原因:for循环是在页面加载的时候就执行完毕了,也就是说当页面加载完毕以后,已经为六个按钮注册了点击事件 ,经过循环以后此时的i 值已经变为了7(  radios[i].style.backgroundColor = "green"  ),但是标签元素数组的长度为6,并不存在第7个标签元素。

解决方法:把这行代码:radios[i].style.backgroundColor = "green"   替换成为  this.style.backgroundColor = "green"  因为this表示当前点击事件绑定的标签元素,指向着的每次点击的按钮

成功:

 

 

 

 

在Web编程中,特别是使用JavaScript等动态语言时,你可以使用for循环来遍历数组并找到最大值、最小值及其对应的索引。下面是一个简单的示例代码解释: ```javascript function findMinMaxAndIndex(arr) { // 初始化变量:最大值(max),最小值(min),最大值的索引(maxIndex),最小值的索引(minIndex) let max = arr[0]; let min = arr[0]; let maxIndex = 0; let minIndex = 0; // 使用for循环遍历数组 for (let i = 1; i < arr.length; i++) { // 检查当前元素是否大于最大值 if (arr[i] > max) { max = arr[i]; // 更新最大值 maxIndex = i; // 当前元素成为新的最大值所在索引 } // 检查当前元素是否小于最小值 if (arr[i] < min) { min = arr[i]; // 更新最小值 minIndex = i; // 当前元素成为新的最小值所在索引 } } // 返回结果:最大值、最小值以及它们的索引 return {max: max, maxIndex: maxIndex, min: min, minIndex: minIndex}; } // 示例数组 const numbers = [5, 2, 9, 1, 7]; // 调用函数,获取最大值、最小值及其索引 const result = findMinMaxAndIndex(numbers); console.log(`最大值 ${result.max} 的索引是 ${result.maxIndex}`); console.log(`最小值 ${result.min} 的索引是 ${result.minIndex}`); ``` 在这个例子中,我们创建了一个名为`findMinMaxAndIndex`的函数,它接受一个数组作为输入,然后逐个比较每个元素,更新最大值和最小值,同时记录它们的索引。最后返回包含这些信息的对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值