jQuery的传递$这功能参数(jQuery pass $this to function para

2019-09-16 14:27发布

我有:

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

任何想法,使悬停事件传递$以此作为暂停功能的参数?

Answer 1:

每次打电话时$ ,它返回一个不同的结果集的对象,即使结果的内容是相同的。 你必须做的检查:

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


Answer 2:

试着像下面,

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


Answer 3:

在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。



Answer 4:

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

无论如何,你不能比较的对象==在JavaScript。 它返回true ,只有当它链接才可同一个对象。

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

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


文章来源: jQuery pass $this to function parameter