[英]Jquery: Use SetInterval when clicking
我有一個簡單的javascript jquery代碼:
我認為它會起作用,但事實並非如此! 我沒有收到任何錯誤或任何錯誤,有誰知道為什么?
var colors = ['red','green','blue'];
$('button').on('click',function(){
var index = $(this).parent().index();
setInterval(function(){
$(this).parent().css('background',colors[index]);
index < 3 ? index++ : index = 0;
}, 1000);
});
HTML代碼
<div class="titleBox">
<button>Click meh!</button>
</div>
<div class="titleBox">
<button>Click meh!</button>
</div>
<div class="titleBox">
<button>Click meh!</button>
</div>
.titleBox {
width:200px;
height:200px;
float:left;
border:1px solid;
opacity:.5
}
.titleBox[style^="background"] {
opacity:1;
}
在setTimeout()
$(this)
之外分配$(this)
,然后通過引用將變量傳遞給timeout函數:
$('button').on('click',function(){
var self = $(this);
var index = $(this).parent().index();
setInterval(function(){
self.parent().css('background',colors[index]);
index < 3 ? index++ : index = 0;
}, 1000);
});
問題是在setInterval
內部, this
通常指向全局對象(窗口),而不是點擊處理程序中的DOM元素。 您有兩種選擇:
保存this
作為一個獨立的變量 ,並使用從setInterval
匿名函數
$('button').on('click',function(){
var self = $(this);
var index = $(this).parent().index();
setInterval(function(){
self.parent().css('background',colors[index]);
index < 3 ? index++ : index = 0;
}, 1000);
});
綁定您的setInterval
處理程序,以便您不會在匿名函數中丟失this
$('button').on('click',function(){
var index = $(this).parent().index();
setInterval(function(){
$(this).parent().css('background',colors[index]);
index < 3 ? index++ : index = 0;
}.bind(this), 1000);
});
這將解決您的問題,以這種方式更改您的js:
$('button').on('click',function(){
var index = $(this).parent().index();
var $el = $(this);
setInterval(function(){
$el.parent().css('background',colors[index]);
index < 3 ? index++ : index = 0;
}, 1000);
});
作為替代方案,既然你有答案,那就是使用作為eventHandler的arguments
傳遞的event
對象(onclick,onchange,...)
$('button').on('click',function(ev){
var index = $(this).parent().index();
setInterval(function(){
$(ev.currentTarget).parent().css('background',colors[index]);
index < 3 ? index++ : index = 0;
}, 1000);
});
現在我注意到你重復一些東西,所以也許你可以這樣做:
$('button').on('click',function(){
var parent = $(this).parent(),
index = parent.index();
setInterval(function(){
parent.css('background',colors[index]);
index < 3 ? index += 1 : index = 0;
}, 1000);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.