【问题标题】:Using jQuery each to grab image height使用 jQuery each 来获取图像高度
【发布时间】:2010-11-19 10:05:04
【问题描述】:

我在一个页面上有一堆图像。我正在尝试使用 jQuery 来获取每个图像的高度并将其显示在图像之后。所以这是我的代码:



$(document).ready(function() {
  $(".thumb").each(function() {
    imageWidth = $(".thumb img").attr("width");
    $(this).after(imageWidth);
  });
});

<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>

[...]


我在 jQuery 背后的逻辑是我想遍历每个“thumb”选择器,将“thumb”内的 img 高度分配给变量“imageWidth”,然后在每个“thumb”之后以文本显示高度.

我遇到的问题是它只处理第一张图像然后退出。当然,如果我使用“thumb_img”类,我可以让它工作,但我需要访问“thumb”类的图像高度。

希望这不会太令人困惑,因为我对 jQuery 还很陌生。提前谢谢。

【问题讨论】:

  • 你的行`imageWidth = $(".thumb img").attr("width");`正在选择所有具有类thumb的div下的所有图像标签,而不仅仅是选择下的图像标签迭代div。

标签: jquery image loops height each


【解决方案1】:

我使用了类似的东西来预加载图像并在 mouseover 和 mouseout 中设置一些代码,并为所有具有类名“swap”的图像设置样式。对我来说$(this) 不起作用,但直接this 起作用了:

// in jquery
$(document).ready(function(){
        swapAndPreload();
    });

function swapAndPreload(){
    $(".swap").each(function(){
        // preload images in cache
        var img = new Image();
        img.src=this.src.replace(/([-_])out/,'$1over');
        //set the hover behaviour
        this.onmouseover = function(){
            this.src=this.src.replace(/([-_])out/,'$1over');
        }
        //set the out behaviour
        this.onmouseout = function(){
            this.src=this.src.replace(/([-_])over/,'$1out');
        }
        //set the cursor style
        this.style.cursor="pointer";
    });
}

【讨论】:

    【解决方案2】:
    $().ready(function() {
    
            $(".thumb img").load(function() {
                var imageHeight = $(this).height();
                $(this).parent().append(imageHeight);
    
            });
    
    });
    

    【讨论】:

    【解决方案3】:

    您将无法使用 document.ready() 来执行此操作,因为图像在调用时尚未加载。

    您实际上需要将此代码放入 onload() 事件处理程序中,该处理程序在文档和所有图像都完成加载后调用。

    只有当图片加载完成后,浏览器才知道它们有多大。

    【讨论】:

    • 谢谢,这解决了我的问题!我不得不使用$(window).load(function()); 而不是$(document).ready(function());
    【解决方案4】:

    使用这个:

    imageWidth = $(this).children("img").attr("width")
    

    以下选择您的所有图像:

    $(".thumb img")
    

    ...所以当你请求属性时,它会从集合中的第一个对象返回它

    抱歉所有的编辑...但最好重用 jquery 对象,所以:

    var $this = $(this)
    

    然后参考 $this 进行优化。在这个例子中没什么大不了的,但这是一个很好的做法。

    【讨论】:

    • 你打败了我的答案。 +1
    • 对不起,哥们,有时确实像一场比赛
    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多