设置变量不工作页面加载,但通过控制台

Setting Variables Does Not Work on Page Load, but Does Through Console?

本文关键字:控制台 加载 变量 工作页 设置      更新时间:2023-09-26

我一定错过了什么。我的脚本如下:

var slideshowUL = jQuery('div.slideshow').css('overflow', 'hidden').children('ul'),
    imgs = slideshowUL.find('img'),
    imgWidth = imgs[0].width,
    imgsLen = imgs.length,
    current = 0;
    console.log(slideshowUL);
    console.log(imgs);
    console.log(imgWidth);
    console.log(imgsLen);
    console.log(current);

输出为:

[ul, prevObject: p.fn.p.init[1], context: document, selector: "div.slideshow.children(ul)", constructor: function, init: function…]
[img, img, img, img, prevObject: p.fn.p.init[1], context: document, selector: "div.slideshow.children(ul) img", constructor: function, init: function…]
0
4
0 

它没有得到图像的宽度。当我将上面的代码直接粘贴到控制台时,它返回正确的值(750)。

Width为0表示您正在读取图像加载之前的值。在window onload上调用它,而不是ready/inline。

图片尚未加载。你必须在图片加载时请求宽度