gpt4 book ai didi

javascript - 使用 jQuery 时维持此范围

转载 作者:行者123 更新时间:2023-11-28 06:41:27 25 4
gpt4 key购买 nike

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

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

现在我用另一个函数扩展了原型(prototype)来计算 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出window.load函数内的that变量,我会得到我期望的值,但由于某种原因运行that.$innerWrap .width(that.innerWrapWidth); 不会设置元素的宽度。我可以确认内部包装绝对是一个 jQuery 对象,并且 innerWidth 绝对是一个整数。

最佳答案

我看来您应该使用以下代码序列:

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

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

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

关于javascript - 使用 jQuery 时维持此范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33768472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com