考虑下面的JavaScript函数:奇怪的JavaScript行为,这里可能会发生什么?
function bs_animate_percentage(elem,style,unit,from,to,time) {
if(!elem) return;
console.log("first elem", elem);
var start = new Date().getTime(),
timer = setInterval(function() {
console.log("second elem", elem);
console.log("time", time);
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if(step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}
此功能为动画加载吧,它是从另一个StackOverflow的问题所采取。我想为动画添加文本更改,为此我需要初始元素的父项。
当运行该函数,使用以下参数,控制台记录以下值:
bs_animate_percentage(document.getElementById("progress-bar"), 'width', '%', 0, 100, 60000);
*** LOGS ***
"first elem", <div....> (the selected div)
"second elem", undefiend
"time", 600000
基本上,主函数内部,ELEM是已知的并且具有预期值。但是在匿名函数中,elem被注销为未定义的,如果我尝试获取它的父类,它也是未定义的,然而,style属性按预期工作,因为elem的宽度正在改变。我在Chrome中遇到过这种情况,这里可能是什么问题?
编辑:我也检查过Firefox,但奇怪的是,有正确的结果传回第二个控制台日志。这必须是Chrome的一些具体的事情,但我不知道是什么...
EDIT2:什么是更奇怪,试图复制在的jsfiddle这种行为时,它不坚持,无论是在浏览器火狐也不。那么我应该在哪里寻找问题?