簡體   English   中英

Jquery:單擊時使用SetInterval

[英]Jquery: Use SetInterval when clicking

我有一個簡單的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)之外分配$(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM