问题描述
我敢肯定,这对于您的jQuery难题将是一个非常简单的答案,而且我也很高兴,它涉及某种循环.
I'm pretty sure this will be a really easy answer for you jQuery whizzes, and I'm also pretty such it involves a loop of some kind.
我试图在两个单独的div上执行基本相同的计算,但是根据找到的图像数为每个id分配不同的CSS宽度值.我正在执行的计算实际上与我的问题无关,但是无论如何我还是把它们放在了一起,因为这是我正在使用的实际代码.
I'm trying to perform essentially the same calculation on two separate divs, but assigning a different CSS width value to each id based on the number of images found. The calculations I'm performing are irrelevant to my problem really, but I put them in anyway because it's the actual code I'm working with.
这里是标记...
<div id ='test1' class='target'>
<div class='scrolling'>
<img/>
<img/>
<img/>
</div>
</div>
<div id ='test2' class='target'>
<div class='scrolling'>
<img/>
<img/>
<img/>
</div>
</div>
下面是我当前使用的jQuery,它可以正常工作,但是效率低下,因为我必须为添加的每个div编写另一段代码.我该如何对其进行标准化,以使其遍历每个具有目标类的div?谢谢
Below is my current jQuery, which works fine, but it's inefficient because I have to write another chunk of code for every div added. How can I standardise this so that it runs through every div with the class of target? Thanks
/* Measure the width of each image. */
test1 = $('#div1 .scrolling img').width();
test2 = $('#div2 .scrolling img').width();
/* Find out how many images there are. */
test1img = $('#div1 .scrolling img').length;
test2img = $('#div2 .scrolling img').length;
/* Do the maths. */
final1 = (test1 * test1img)*1.2;
final2 = (test2 * test2img)*1.2;
/* Apply the maths to the CSS. */
$('#div1 .scrolling').width(final1);
$('#div2 .scrolling').width(final2);
推荐答案
像这样:
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.width();
var imgLength = images.length;
$(this).find(".scrolling").width( width * imgLength * 1.2 );
});
$(this)
表示将循环通过的当前.target
.在此.target
中,我正在寻找.scrolling img
并获取宽度.然后继续前进...
The $(this)
refers to the current .target
which will be looped through. Within this .target
I'm looking for the .scrolling img
and get the width. And then keep on going...
具有不同宽度的图像
如果要计算所有图像的宽度(当它们具有不同的宽度时),可以这样:
If you want to calculate the width of all images (when they have different widths) you can do it like this:
// Get the total width of a collection.
$.fn.getTotalWidth = function(){
var width = 0;
this.each(function(){
width += $(this).width();
});
return width;
}
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.getTotalWidth();
$(this).find(".scrolling").width( width * 1.2 );
});
这篇关于jQuery遍历每个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!