javascript jQuery 将 $this 传递给函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10198768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery pass $this to function parameter
提问by jaredrada
I have:
我有:
<img id="leftBubble" class="bubbles" src="left.png" />
<img id="rightBubble" class="bubbles" src="right.png" />
And a hover event like so:
还有一个像这样的悬停事件:
$(".bubbles").each(function(){
$(this).hover(function() {
pause($(this));
}, function() {
play(4000, $(this));
});
});
My pause() function does not seem to be working
我的 pause() 功能似乎不起作用
function pause(pauseMe) {
if (pauseMe == $("#leftBubble")) {
clearTimeout(timer1); //this is never reached
} else if (pauseMe == $("#rightBubble")) {
clearTimeout(timer2); //nor this
}
}
Any idea to make the hover event pass $this as the parameter for the pause function?
任何想法让悬停事件通过 $this 作为暂停函数的参数?
回答by Ates Goral
Each time you call $
, it returns a different result set object, even if the result contents are the same. The check you have to do is:
每次调用 时$
,它都会返回不同的结果集对象,即使结果内容相同。您必须做的检查是:
if (pauseMe.is("#leftBubble")) {
回答by Selvakumar Arumugam
Try like below,
尝试如下,
function pause(pauseMe) {
if (pauseMe == "leftBubble") {
clearTimeout(timer1);
} else if (pauseMe == "rightBubble") {
clearTimeout(timer2);
}
}
and in the caller,
在来电者中,
$(".bubbles").each(function(){
$(this).hover(function() {
pause(this.id);
}, function() {
play(4000, $(this));
});
});
回答by Roman Pominov
When you call $( ... )
it generates new object that not the same that was genereted when you call $( ... )
last time, with same parametrs.
当您调用$( ... )
它时,生成的新对象与您$( ... )
上次调用时生成的对象不同,具有相同的参数。
Anyway, you can't compare objects with ==
in javascript. It returns true
only if it liks on same object.
无论如何,您无法与==
javascript 中的对象进行比较。true
仅当它喜欢同一个对象时才返回。
a = {b:1}
c = {b:1}
d = c
a == b // false
d == c // true
回答by Juan Enrique Mu?oz Zolotoochin
In javascript, this
is redefined each time you enter a new function definition. If you want to access the outsidethis
, you need to keep a reference to it in a variable (I used the self
) variable.
在 javascript 中,this
每次输入新的函数定义时都会重新定义。如果要访问外部this
,则需要在变量(我使用self
)变量中保留对它的引用。
$(".bubbles").each(function(){
var self = this;
$(this).hover(function() {
pause($(self));
}, function() {
play(4000, $(self));
});
});
I don't know if your comparison between jQuery objects will work though. Maybe you can compare the DOM elements: pauseMe[0] == $("#leftBubble")[0]
, or, as mentioned, the ids.
我不知道您在 jQuery 对象之间的比较是否有效。也许您可以比较 DOM 元素:pauseMe[0] == $("#leftBubble")[0]
,或者,如上所述,ids。