2013-12-22 64 views
0

我有一個問題使用jquery鼠標懸停改變PIC src屬性,當我做到這一切工作正常:爲什麼它不改變這個「循環」內的圖像?

$(this).attr('src',currURL+"_0"+currPicID+'i.jpg'); 

但是當循環開始src屬性也發生了變化,但畫面(我是指視覺上)不(尋找螢火蟲cosnole),但我看到的變化做像這樣src屬性的簡單警報:

this.iid = setInterval(function() { 
currPicID++; 
if (currPicID>16){currPicID=1;} 
$(this).attr('src',currURL+"_0"+currPicID+'i.jpg'); 
alert($(this).attr('src')); <=== this changes perfectly and shows correct paths 
}, 525); 

還對鼠標懸停它工作正常:

bind('mouseleave', function(){ 
this.iid && clearInterval(this.iid); 
$(this).attr('src', oriPIC) 

有關我做錯什麼的建議?

謝謝!

+1

與論壇網站不同,我們不使用「謝謝」或「任何幫助表示讚賞」,或對[so]進行簽名。請參閱[應該'嗨','謝謝',標語和致敬辭職](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-刪除 - 從 - 個)。 – rene

回答

1

您的問題是最有可能this該區間內的回調將是全球範圍內(窗口或未定義),並在你的情況你是剛剛設置窗口的src屬性,而不是圖像。相反,在回調之前將當前圖像對象緩存在變量中並使用它。

var $img = $(this); 
this.iid = setInterval(function() { 
    currPicID++; 
    if (currPicID > 16) { 
     currPicID = 1; 
    } 
    $img.attr('src', currURL + "_0" + currPicID + 'i.jpg'); 
    alert($img.attr('src')); //<= == this changes perfectly and shows correct paths 
}, 525); 

或者使用$.proxy或function.bind綁定的回調函數的上下文。

this.iid = setInterval($.proxy(function() { 
    currPicID++; 
    if (currPicID > 16) { 
     currPicID = 1; 
    } 
    $(this).attr('src', currURL + "_0" + currPicID + 'i.jpg'); 
    alert($(this).attr('src')); <= == this changes perfectly and shows correct paths 
},this), 525); 
+0

工作!用$ .proxy並設置this.id,謝謝! – Mark

+0

@M歡迎您... – PSL