【问题标题】:this scope maintained when using jQuery使用 jQuery 时维护此范围
【发布时间】:2016-02-19 12:06:55
【问题描述】:

我有一个设置一些默认属性的对象

var Gallery = function(container, opts) {
 this.$innerWrap = null;
 this.innerWrapWidth = 0;
 this.$slides = $(el).find('img');
};

现在,稍后我用另一个函数扩展原型来计算this.innerWrapWidth 的宽度,这是通过计算$innerWrap 内的所有图像并将它们加在一起来完成的。

我有一个问题,但与范围有关,这是我的功能:

Gallery.prototype.calcWrapWidth = function() {
 var that = this;

 $(window).on('load', function() {
  $.each(that.$slides, function() {
   var slide = $(this);
   that.innerWrapWidth += slide.width();
  });
  that.$innerWrap.width(that.innerWrapWidth);
 });
 console.log(this.innerWrapWidth)
};

理想情况下,我会遍历数组中的所有图像,获取宽度并将其设置在属性 this.innerWrapWidth 上,然后将值添加到 this.$innerWrap

我尝试设置var that = this;

但是当我运行 console.log 时,我得到 0 作为值返回。我找不到在this.innerWrapWidth上设置最终宽度的最佳方法

更新:

我已经缩小范围了!如果我 console.log out window.load 函数内的 that 变量,我会得到我期望的值,但由于某种原因,运行 that.$innerWrap.width(that.innerWrapWidth); 不会设置元素的宽度。我可以确认内部包裹绝对是一个 jQuery 对象,innerWidth 绝对是一个整数。

【问题讨论】:

  • 我认为您的问题与thisthat 无关。 (至少不是this...)。您是否尝试过that.$slides.each(...)?不确定$.eachthis 有什么特别之处。另外,el 是在哪里定义的? Ans 当所有图像都存在时执行此代码吗?
  • 这一行:this.$slides $(el).find('img') 不是表达式或语句
  • 谢谢@Tomanow 我已经在示例中更新了
  • @FelixKling 我没有,但可以尝试添加 that.$slides.each。 el 是在同一个对象中定义的,为了简洁起见,我将其省略。
  • 呃等等...目前console.log(this.innerWrapWidth) 在事件处理程序的外部。该行将在您迭代所有元素之前执行。但是,that.$innerWrap.width(that.innerWrapWidth); 应该可以正常工作。

标签: javascript jquery scope this


【解决方案1】:

我看来你应该使用下面的代码序列:

$(window).on('load', function() { 
  var myGal = new Gallery(..);
  myGal.calcWrapWidth();
});

并从calcWrapWidth 方法中删除$(window).on('load', function() { 代码行。

这可确保在执行计算时所有元素都显示在页面上。

【讨论】:

  • window.onload$(window).on('load', ...) 有什么区别?
  • 那你为什么建议改变它呢?
  • 没错,这似乎更合理,但看起来应该没什么大不了的。无论哪种方式,我都建议在您的答案中添加解释。
  • 感谢@MaxZoom,但我不想在实例化画廊时调用单独的方法,我认为如果它在主调用中完成会更好
  • @SamMason 我不知道main call 是什么意思,是Gallery 构造函数吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 2016-06-22
  • 2021-06-11
相关资源
最近更新 更多