我在页面上有很多图像。我正在尝试使用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背后的逻辑是,我想通过每个“拇指”选择器,将“拇指”内部的img的高度分配给变量“ image Width”,然后在每个“拇指”之后显示文本中的高度。

我遇到的问题是它仅在第一个图像上工作然后退出。当然,如果使用“ Thumb_img”类,我可以使它起作用,但是我需要访问“拇指”类的图像高度。

希望这不会太混乱,因为我对jQuery来说是新手。谢谢进步。

有帮助吗?

解决方案

用这个:

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

以下选择您的所有图像:

$(".thumb img")

...因此,当您要求属性时,它会从集合中的第一个对象返回

对不起所有的编辑...但是最好重复使用jQuery对象,所以:

var $this = $(this)

然后参考$这是优化所需的。在此示例中,这不是很大的交易,但这是一种很好的做法。

其他提示

您将无法使用document.ready()来执行此操作,因为图像不会在所谓的时间内加载。

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

只有当图像完成加载时,浏览器才知道它们的大小。

$().ready(function() {

        $(".thumb img").load(function() {
            var imageHeight = $(this).height();
            $(this).parent().append(imageHeight);

        });

});

我已经使用了类似的东西来预紧图像并在鼠标和鼠标中设置一些代码,并为所有图像设置了所有图像的样式,并具有“ 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";
    });
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top