在函数中使用jQuery $(this) [英] Using jquery $(this) in a function

查看:128
本文介绍了在函数中使用jQuery $(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速说明: 我知道在函数中使用$(this)无效,因为它不在正确的范围内.我也看到了其他类似的问题.我只是仍然不知道如何解决我的问题.

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.

目标:我正在尝试使用jQuery构建全景照片查看器.我有它的工作,但我需要多个实例.因此,我只需要定位要悬停的那个.

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.

代码:

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

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

简化代码:

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

推荐答案

您遇到范围问题,在doStuff中是窗口上下文.

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

使用 proxy()

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

这篇关于在函数中使用jQuery $(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆