Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - Using jquery $(this) in a function

Quick Description: I'm aware that using $(this) in a function won't work because it's not within the right scope. I've also seen other similar questions. I just still can't figure out how to fix my scenerio.

Goal: I'm trying to build a panoramic photo viewer with jQuery. I have it working, but I need multiple instances. So I need to target only the one I'm hovering on.

Code:

jsFiddle: http://jsfiddle.net/kthornbloom/5J3rh/

Simplified Code:

var hoverInterval;

function doStuff() {

/* The next line is the one in question */

    $(this).animate({
      /* stuff happening */
    });
}

$(function() {
    $('.pan-wrap').hover(
        function() {
            /* stuff happening */
            hoverInterval = setInterval(doStuff, 250);
        },
        function() {
            clearInterval(hoverInterval);
   });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have scope issues, this in the doStuff is window context.

Use proxy()

hoverInterval = setInterval($.proxy(doStuff,this), 250);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...