2012-04-17 101 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