2
我需要使用setInterval创建多个同时具有不同速度频率的动画对象,并使用相同的构造函数生成。我面临的问题是,在创建2个或更多对象后,传递给setInterval的对象的方法始终引用最后创建的对象。贝娄是我想要达到一个例子:同时多次调用setInterval在javascript中具有相同构造函数的对象内
function obj(s){
this.speed = s;
this.colors = ["FF0000","FF3300","FF6600","FF9900","FFCC00","FFFF00","FFCC00"];
_this = this;
this.counter = 0;
this.genDiv = function(){
this.div = document.createElement('div');
this.div.style.width = 100 + "px";
this.div.style.height = 100 + "px";
document.body.appendChild(this.div);
setInterval(function(){_this.div.style.backgroundColor = "#" + _this.colors[_this.globalCounter()]}, _this.speed);
};
this.globalCounter = function(){
if(this.counter <= (this.colors.length-1)){
return this.counter++;
}else{
this.counter = 1;
return 0;
}
};
}
window.onload = start;
function start(){
var a = new obj(1000);
var b = new obj(2000);
a.genDiv();
b.genDiv();
}
运行此代码后,两个setIntervals调用动画只有对象b。使用简单的函数,它工作正常,但我想自己的内容动画对象可以填充和独立运行。谢谢。
可能的重复http://stackoverflow.com/questions/1451009/javascript-infamous-loop-problem – 2012-03-01 15:06:47