JQuery - 在事件处理程序中访问对象属性

时间:2012-05-18 14:10:18

标签: javascript jquery

我正在尝试使用jquery对div进行扩展。 该扩展名称为NunoEstradaViewer,下面是代码示例:

(function ($){

NunoEstradaViwer: {
  settings: {
     total: 0,
     format: "",
     num: 0;
  },
  init: function (el, options) {
   if (!el.length) { return false; }
        this.options = $.extend({}, this.settings, options);
        this.itemIndex =0;
        this.container = el;

        this.total = this.options.total;
        this.format = ".svg";
        this.num = 0;
  },
  generateHtml: function(){
   /*GENERATE SOME HTML*/

  $("#container").scroll(function(){
        this.num++;
        this.nextImage;
  })
  },
  nextImage: function(){

  /*DO SOMETHING*/

  }
});

我的问题是我需要访问this.num的值并在scroll事件的处理函数内调用this.nextImage函数,但是对象“this”指的是滚动而不是“NunoEstradaViewer” 。我如何访问这些元素?

谢谢

2 个答案:

答案 0 :(得分:2)

通常我在这种情况下所做的是在变量中保存对“this”的引用。

generateHtml: function(){
    /*GENERATE SOME HTML*/

    var self = this;

    $("#container").scroll(function(){
        self.num++;
        self.nextImage;
    })
}

答案 1 :(得分:1)

常见的解决方案是存储对所需上下文的引用:

(function () {
    var self;
    self = this;
    $('#container').scroll(function () {
        self.doStuff();
    });
}());

另一种方法是将上下文传递给函数:

(function () {
    $('#container').scroll({context: this, ..more data to pass..}, function (e) {
        e.data.context.doStuff();
    });
    //alternatively, if you're not passing any additional data:
    $('#container').scroll(this, function (e) {
        e.data.doStuff();
    });
}());