【问题标题】:Using jquery $(this) in a function在函数中使用 jquery $(this)
【发布时间】:2013-04-11 16:34:46
【问题描述】:

简要说明: 我知道在函数中使用 $(this) 是行不通的,因为它不在正确的范围内。我还看到了其他类似的问题。我仍然无法弄清楚如何修复我的场景。

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

代码:

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

【问题讨论】:

  • 我知道在函数中使用 $(this) 是行不通的,因为它不在正确的范围内。 — 范围无关紧要。重要的是上下文。
  • 使用 $.proxy() 函数设置 this 的上下文。
  • 看看这个小提琴jsfiddle.net/5J3rh/4

标签: javascript jquery


【解决方案1】:

您有范围问题,doStuff 中的 this 是窗口上下文。

使用proxy()

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

【讨论】:

  • 哦,太好了!我不知道proxy()。 +1
  • 谢谢,这是我正在寻找的缺失部分。
【解决方案2】:

您可以将this 显式传递给doStuff

setInterval(function() {
    doStuff(this);
}, 250);

doStuff 你可以这样做:

function doStuff(element) {
    ...
}

或者您可以像这样为doStuff 显式设置this 的值:

setInterval(function() {
    doStuff.call(this);
}, 250);

那么你仍然可以在doStuff 中使用$(this) 而无需更改其任何参数。有关call 的更多信息,请参阅Function.prototype.call 及其朋友Function.prototype.apply

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    相关资源
    最近更新 更多