繁体   English   中英

jQuery将$ this传递给函数参数

[英]jQuery pass $this to function parameter

我有:

<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));
    });
});

我的pause()函数似乎不起作用

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

任何想要使悬停事件传递$ this作为暂停函数的参数?

每次调用$ ,它都会返回不同的结果集对象,即使结果内容相同也是如此。 您需要做的检查是:

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

试试如下,

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));
  });
});

在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] ,或者如上所述,ids。

当你调用$( ... )会生成新的对象,不是,当你呼叫genereted相同$( ... )最后一次,同parametrs。

无论如何,你无法在javascript中将对象与==进行比较。 只有当它在同一个对象上时,它才返回true

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM