我有一个简单的 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)
,然后通过引用将变量传递给超时函数:
$('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);
});
关于javascript - Jquery:点击时使用SetInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23526790/