jQuery pass $this to function parameter

流过昼夜 提交于 2019-12-14 02:10:22

问题


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

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?


回答1:


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")) {



回答2:


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



回答3:


In javascript, this is redefined each time you enter a new function definition. If you want to access the outside this, you need to keep a reference to it in a variable (I used the self) variable.

$(".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.




回答4:


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.

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

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


来源:https://stackoverflow.com/questions/10198768/jquery-pass-this-to-function-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!