javascript - Jquery:点击时使用SetInterval

标签 javascript jquery html css

我有一个简单的 javascript jquery 代码:

http://jsfiddle.net/reX2N/

我以为它会起作用,但它不是!我没有收到任何错误或任何信息,有人知道为什么吗?

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),然后通过引用将变量传递给超时函数:

Example Here

$('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/

相关文章:

php - Google Analytics - 我可以将脚本放在页脚中吗?

jquery - 关于JSSOR Slider的几个问题

java - 如何将信息发送到jsp中的辅助函数?

javascript - Google +1 按钮未打开 "share this"气泡

java - 监听 Javascript 函数调用 - Android

javascript - 有没有办法获得位置 :absolute elements? 的继承宽度

jquery - jqPlot - 无法将 x 轴显示为右侧图例

html - css - Bootstrap - 在导航栏中将表单与表单控制 input-sm 垂直对齐

javascript - div 中的 child 点。令人头疼的 jQuery

jQuery.animate 很难从右到左移动一个 div