扫码关注官方订阅号
Document
光阴似箭催人老,日月如移越少年。
@小_秦 已经指出问题了,也提供了解决方法。我再补充两种,其他朋友如果有其他方法的话不妨贴上来。
/* var timer = null; op = document.getElementsByTagName("p"); for (var i = 0; i < 3; i++) { op[i].onmouseover = function() { var _this=this; timer = setInterval(function() { _this.style.height = _this.offsetHeight + 2 + 'px' }, 30); //方法一:避免在闭包里面引用外包函数的变量,用this来代替 } op[i].onmouseout = function() { clearInterval(timer); } } */ //=================================================================== /* var timer = null; op = document.getElementsByTagName("p"); for (var i = 0; i < 3; i++) { op[i].onmouseover = function() { timer = setInterval(function() { this.style.height = this.offsetHeight + 2 + 'px' }.bind(this), 30); //方法一改良 } op[i].onmouseout = function() { clearInterval(timer); } } */ //=================================================================== var timer = null; op = document.getElementsByTagName("p"); function test(i) { timer = setInterval(function() { op[i].style.height = op[i].offsetHeight + 2 + 'px' }, 30) }; for (var i = 0; i < 3; i++) { op[i].onmouseover = function(num){ return function() { test(num); } }(i); //方法二:用iife来替换,事实上,就是用iife的形参作为桥梁在两个作用域之间传值 op[i].onmouseout = function() { clearInterval(timer); } }
1.楼主最好去学习一下MARKDOWN怎么写。2.这个是闭包陷阱
你可以使用闭包实验一下你这个for绑定事件肯定不对的,绑定的i都是3所以肯定op[3]都是不存在的,
1)p1,#p2,#p3{width:200px;height:200px;background:red;margin:10px;}==》#p1,#p2,#p3{width:200px;height:200px;background:red;margin:10px;}2)p,mouseover事件触发函数中的i为3,这里涉及到js中变量作用域3) p的事件绑定推荐使用代理的方式-不用为每一个p绑定事件回调
p1,#p2,#p3{width:200px;height:200px;background:red;margin:10px;}
#p1,#p2,#p3{width:200px;height:200px;background:red;margin:10px;}
timer = null; 后面应该是逗号
var timer=null, op=document.getElementsByTagName("p");
你声明变量时,要用var,如果是全局变量时函数内部不用var,儿最外层原始变量需要var的,这段代码,错误百出啊,以上楼层说了闭包的问题,就不多说了
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
@小_秦 已经指出问题了,也提供了解决方法。我再补充两种,其他朋友如果有其他方法的话不妨贴上来。
1.楼主最好去学习一下MARKDOWN怎么写。
2.这个是闭包陷阱
你可以使用闭包实验一下你这个for绑定事件肯定不对的,绑定的i都是3所以肯定op[3]都是不存在的,
1)
p1,#p2,#p3{width:200px;height:200px;background:red;margin:10px;}==》
#p1,#p2,#p3{width:200px;height:200px;background:red;margin:10px;}2)p,mouseover事件触发函数中的i为3,这里涉及到js中变量作用域
3) p的事件绑定推荐使用代理的方式-不用为每一个p绑定事件回调
timer = null; 后面应该是逗号
你声明变量时,要用var,如果是全局变量时函数内部不用var,儿最外层原始变量需要var的,这段代码,错误百出啊,以上楼层说了闭包的问题,就不多说了