猿问

这个错误是为什么啊?

目的是想让二级菜单下的图片做一个margin-left的缩入

script标签页放在body之后的,报错是
Uncaught TypeError: Cannot read property 'classList' of undefined
at HTMLButtonElement.btnaaaaaaa.onclick

btnaaaaaa这个按钮是加上去测试的。。。


MM们
浏览 494回答 1
1回答

www说

闭包问题,你把k打印出来就知道了,你的k始终为lan,rotatGroup[lan]肯定是undefinedfor (var k=0;k<lan;k++){&nbsp; &nbsp; (function(k){&nbsp; &nbsp; &nbsp; &nbsp; btnaaaaaa.onclick = function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rotatGroup[k].classList.toggle('rotate')&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })(k)};你的意图可能是:&nbsp; &nbsp; btnaaaaaa.onclick = function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (var k=0;k<lan;k++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rotatGroup[k].classList.toggle('rotate');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答