JQuery - 事件处理程序中的 accessss 对象属性

JQuery - acess object property inside event handler

本文关键字:accessss 对象 属性 事件处理 程序 JQuery      更新时间:2023-09-26

我正在尝试使用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 的值并在滚动事件的处理程序函数中调用函数 this.nextImage,但对象"this"指的是滚动而不是"NunoEstradaViewer"。如何访问这些元素?

谢谢

通常在这种情况下,我所做的是将"this"的引用保存在变量中。

generateHtml: function(){
    /*GENERATE SOME HTML*/
    var self = this;
    $("#container").scroll(function(){
        self.num++;
        self.nextImage;
    })
}

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

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