【问题标题】:Access variable from load function从加载函数访问变量
【发布时间】:2012-10-19 18:50:45
【问题描述】:

这里是一个函数的 sn-p。我正在获取每个图像的原始大小。然后我想做一个简单的 if 语句,但不能访问变量'imageWidth'。在“theImage.onload = function()”之外获取“未定义”。怎么会超出范围?

    var parentWidth = $('figure.pack_image').width();
    var screenImage = $('figure.pack_image img');
    var imageWidth = '';

    screenImage.each(function () {

        var theImage = new Image();
        theImage.src = $(this).attr('src');

        theImage.onload = function() {
            imageWidth = this.width;

        }

        if (imageWidth > parentWidth) {
        ...

【问题讨论】:

    标签: jquery function variables scope global


    【解决方案1】:

    它不是“超出范围”,只是还没有价值。在设置 imageWidth 之前,您无法对其进行测试,并且 .onload 调用是异步的。

    您的测试需要在 .onload 函数内启动:

    theImage.onload = function() {
        imageWidth = this.width;
        if (imageWidth > parentWidth) {
            ...
        }
    }
    

    或者,使用延迟回调从后续处理中取消嵌套onload 逻辑:

    var gotImage = $.Deferred();
    theImage.onload = function() {
        gotImage.resolve(this);
    }
    
    gotImage.done(function(img)) {
        if (img.width > parentWidth) {
             ...
        }
    });
    

    【讨论】:

    • 嘿,谢谢。我之前已经完成了您的第一个解决方案,但这又产生了另一个问题。不过现在都完成了,
    • @user924248 我将稍微重写第二个版本以传递图像对象本身,而不是其宽度。这将使该方法在未来更加灵活。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2017-05-25
    • 2022-01-10
    • 1970-01-01
    • 2021-12-12
    • 2013-09-13
    相关资源
    最近更新 更多