87,715
社区成员




<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
function aaa(obj){
clearInterval(obj.timer); //这样写报错
obj.timer=setInterval(function(){
console.log('121231321');
},10);
}
<!--這個是把定時器綁定在dom元素上-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin:0;padding:0;}
.test1{height:30px;margin:20px auto;text-align:center;background-color:#aaa;}
</style>
<script type="text/javascript">
function time() {
if(typeof this.timer != 'undefined') {
clearInterval(this.timer);
}
this.start = 0;
this.timer = setInterval((function(o) {
return function() {
o.start += 1;
o.innerHTML = o.start;
}
})(this), 500);
}
window.onload = function() {
var i, size;
var nodes = document.getElementsByClassName('test1');
for(i = 0, size = nodes.length; i < size; i++) {
nodes[i].onclick = time;
}
}
</script>
</head>
<body>
<div class="test1"></div>
<div class="test1"></div>
<div class="test1"></div>
</body>
</html>
<!--這個是用一個局部變量保存定時器-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin:0;padding:0;}
.test1{height:30px;margin:20px auto;text-align:center;background-color:#aaa;}
</style>
<script type="text/javascript">
function time(node) {
if(typeof this.timer != 'undefined') {
clearInterval(this.timer);
}
this.start = 0;
this.timer = setInterval((function(o, t) {
return function() {
t.start += 1;
o.innerHTML = t.start;
}
})(node, this), 500);
}
window.onload = function() {
var i, size;
var nodes = document.getElementsByClassName('test1');
var temps = {};
for(i = 0, size = nodes.length; i < size; i++) {
temps[i] = {};
nodes[i].onclick = (function(index) {
return function() {
time.call(temps[index], this);
};
})(i);
}
}
</script>
</head>
<body>
<div class="test1"></div>
<div class="test1"></div>
<div class="test1"></div>
</body>
</html>
window.onload = function(){
var btn = document.getElementsByClassName("dov1"),
len = btn.length;
for(var i = 0; i <len; i++){
var obj = btn[i];
obj.addEventListener ("click",function(obj){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
console.log('121231321');
},10);
})
}
}
function Aaa(){
//code
setTimeOut(Aaa,time);
}
Aaa();
[/quote]
感谢回复,是这样的,我的意思是
我所在的环境里面,使用obj.timer这种写法会报错
不用纠结用哪个定时器
我只是想知道,除了obj.timer这种写法,还有什么代替的写法
可以分别给对象绑定不同的定时器
function Aaa(){
//code
setTimeOut(Aaa,time);
}
Aaa();