2010-05-10 39 views
1

jQuery 1.4.2:使用setInterval和clearInterval調用.live()問題的jQuery事件

我有一個圖像。當mouseover事件被觸發時,執行一個函數來運行一個循環來加載多個圖像。相反,mouseout事件需要將圖像設置回預定圖像,不再執行循環。這些只是使用類「拇指」的圖像:

$("img.thumb").live("mouseover mouseout", function(event) { 
    //var foo = $(this).attr('id'); 
    var wait; 
    var i=0; 
    var image = document.getElementById(foo); 

    if (event.type == 'mouseover') { 
     function incrementimage() 
     { 
      i++; 
      image.src = 'http://example.com/images/file_'+i+'.jpg'; 
      if(i==30) {i=0;} 
     }  
     wait = setInterval(incrementimage,500); 
    } else if (event.type == 'mouseout') { 
     clearInterval (wait); 
     image.src = 'http://example.com/images/default.jpg'; 
    } 
    return false; 
}); 

當我鼠標移開,圖像設置爲default.jpg但是瀏覽器繼續循環,雖然圖像。它永遠不會停止。有人可以用一些知識打我嗎?謝謝。

回答

1

問題是mouseout事件沒有看到與mouseover事件相同的wait。你需要把它存儲在別的地方。我建議使用[data()][1]將其存儲在元素上。

而且,這個順序是沒有意義的:

var foo = $(this).attr('id'); 
... 
var image = document.getElementById(foo); 

this已經是圖像元素。

最後,這不是我如何定義函數。嘗試是這樣的:

$("img.thumb").live("mouseover", function(evt) { 
    var wait = $(this).data("wait"); 
    if (!wait) { 
    clearInterval(wait); 
    } 
    var i = 0; 
    var image = this; 
    var incrementImage = function() { 
    i++; 
    image.src = "http://example.com/images/file_" + i + ".jpg"; 
    if (i == 30) { 
     i = 0; 
    } 
    } 
    wait = setInterval(incrementImage, 500); 
    $(this).data("wait", wait); 
    return false; 
}); 

$("img.thumb").live("mouseout", function(event) { 
    var wait = $(this).data("wait"); 
    if (wait) { 
    clearInterval(wait); 
    } 
    img.src = "http://example.com/default.jpg"; 
    return false; 
}); 
0

您是否嘗試過移動你的​​您.live()的外部事件?

var wait 
$("img.thumb").live("mouseover mouseout", function(event) { 
2

您可以縮短你的代碼到這個正確清除間隔:

$("img.thumb").live("mouseover", function() { 
    var i = 0, image = this, incrementimage = function() { 
    i++; 
    image.src = 'http://example.com/images/file_'+i+'.jpg'; 
    if(i==30) {i=0;} 
    }; 
    $(this).data('timer', setInterval(incrementimage,500)); 
}).live("mouseout", function() { 
    clearInterval($(this).data('timer')); 
    this.src = 'http://example.com/images/default.jpg'; 
}); 

此拆分.live()調用,使邏輯有點清潔,並存儲元件上一wait ID本身使用.data()而不是全局變量。

+0

哇!這真的很性感。尼克做得很好。 – gurun8 2010-05-10 03:51:14