2012-04-17 130 views
2

我:

<img id="leftBubble" class="bubbles" src="left.png" /> 
<img id="rightBubble" class="bubbles" src="right.png" /> 

而且懸停事件,像這樣:

$(".bubbles").each(function(){ 
    $(this).hover(function() { 
     pause($(this)); 
    }, function() { 
     play(4000, $(this)); 
    }); 
}); 

我暫停()函數似乎並不奏效

function pause(pauseMe) { 
    if (pauseMe == $("#leftBubble")) { 
     clearTimeout(timer1);      //this is never reached 
    } else if (pauseMe == $("#rightBubble")) { 
     clearTimeout(timer2);      //nor this 
    } 
} 

任何想讓懸停事件傳遞$ this作爲暫停函數的參數?

+0

jQuery的平等最好用'。是( 「選擇」)'完成:看http://stackoverflow.com/questions/2448291/how-to-check-for-dom-equality-with-jquery/2448362#2448362 – 2012-04-17 20:41:55

+0

比較jquery對象:http://stackoverflow.com/questions/2436966/how-would-you-compare-jquery-objects – malletjo 2012-04-17 20:42:47

回答

4

每次調用$時,即使結果內容相同,也會返回不同的結果集對象。你必須做的檢查:

if (pauseMe.is("#leftBubble")) { 
0

在JavaScript中,this每次你進入一個新的函數定義的時間重新定義。如果您想訪問this之外的,則需要在變量(我使用self)變量中保留對其的引用。

$(".bubbles").each(function(){ 
    var self = this; 
    $(this).hover(function() { 
     pause($(self)); 
    }, function() { 
     play(4000, $(self)); 
    }); 
}); 

我不知道你的jQuery對象之間的比較是否可以工作。也許你可以比較DOM元素:pauseMe[0] == $("#leftBubble")[0],或者,如上所述,ID。

+1

在這種情況下,外部'this'和內部'this'將是相同。 – 2012-04-17 20:45:52

4

嘗試像下面,

function pause(pauseMe) { 
    if (pauseMe == "leftBubble") { 
     clearTimeout(timer1); 
    } else if (pauseMe == "rightBubble") { 
     clearTimeout(timer2); 
    } 
} 

,並在調用者,

$(".bubbles").each(function(){ 
    $(this).hover(function() { 
    pause(this.id); 
    }, function() { 
    play(4000, $(this)); 
    }); 
}); 
+0

這是最有意義的。使用'.is()'似乎是矯枉過正的。 – 2012-04-17 20:57:16

+0

其實我需要對象本身作爲參數,而不是Id – jaredrada 2012-04-18 01:31:05

0

當你調用$(...)它生成新的對象,而不是當你調用$(...)最後一次被genereted一樣,用相同的參數。

無論如何,您無法在javascript中將對象與==進行比較。僅當它在同一個對象上喜歡時,它纔會返回true

a = {b:1} 
c = {b:1} 
d = c 

a == b // false 
d == c // true