var trs = document.getElementsByTagName('tr');
for(var i = 0;i < trs.length;i++){
trs[i].onmouseover = function(){
this.style.backgroundColor = 'grey';
}
trs[i].onmouseout = function(){
this.style.backgroundColor = 'white';
}
}
请问函数中的this为什么不能换成trs[i]
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果函数中的this换成trs[i],对应的绑定事件触发时,i已经变成trs.length了,这样就不是对应的元素了。
闭包问题呀..
i会停留在最终值trs.length上
于是变成了hover只改变trs[trs.length]的样式
当然,这个元素是没有的,index溢出
楼上讲的对,就是for循环执行完了,i变成了trs.length。此时你再去触发函数,显然就不是你想要的当前元素背景变色了