使用jQuery分别获取图像高度 [英] Using jQuery each to grab image height

查看:72
本文介绍了使用jQuery分别获取图像高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bunch of images on a page. I'm trying to use jQuery to grab the height of each image and display it after the image. So here is my code:


$(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的高度分配给变量"imageWidth",然后在每个拇指"之后以文本形式显示高度

My logic behind the jQuery is that I want to go through each "thumb" selector, assign the height of the img inside "thumb" to the variable "imageWidth", and then display the height in text after each "thumb".

我遇到的问题是,它只能在第一个图像上工作,然后退出.当然,如果我使用"thumb_img"类,它可以正常工作,但是我需要访问"thumb"类的图像高度.

The problem I'm having is that it's only working on the first image and then quitting. I can get it to work if I use the "thumb_img" class, of course, but I need access to the height of the image for the "thumb" class.

希望这并不太令人困惑,因为我对jQuery相当陌生.谢谢.

Hopefully this isn't too confusing as I'm fairly new to jQuery. Thanks advance.

推荐答案

使用此:

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

以下内容将选择您的所有图像:

The following selects all your images:

$(".thumb img")

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

... so when you ask for the attribute it returns it from the first object in the collection

对不起,所有编辑...但是最好重用jquery对象,所以:

Sorry for all the edits... but it is best to reuse jquery objects, so:

var $this = $(this)

然后参考$ this进行优化.在这个例子中没什么大不了的,但是使用是一个好习惯.

Then refer to $this were needed for optimization. Not that big a deal in this example, but it is a good practice to use.

这篇关于使用jQuery分别获取图像高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆