jQuery遍历每个div

我很确定这对你来说是一个非常简单的答案jQuery wizzes,而且我也很漂亮,它涉及到某种循环。

我试图在两个单独的div上执行基本相同的计算,但是根据找到的图像数量为每个id分配不同的CSS宽度值。 我正在执行的计算与我的问题无关,但无论如何我都把它们放进去,因为它是我正在使用的实际代码。

这是标记……

下面是我目前的jQuery,它工作正常,但它效率低,因为我必须为每个添加的div编写另一块代码。 我如何标准化它,以便它通过目标类运行每个div? 谢谢

 /* 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并获得宽度。 然后继续……

宽度不同的图像

如果要计算所有图像的宽度(当它们具有不同的宽度时),您可以这样做:

 // 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 ); }); 

你是对的,它涉及一个循环,但这至少可以通过使用each()方法变得简单:

 $('.target').each( function(){ // iterate through each of the `.target` elements, and do stuff in here // `this` and `$(this)` refer to the current `.target` element var images = $(this).find('img'), imageWidth = images.width(); // returns the width of the _first_ image numImages = images.length; $(this).css('width', (imageWidth*numImages)); }); 

参考文献:

  • css()
  • each()
  • find()
 $('div.target').each(function() { /* Measure the width of each image. */ var test = $(this).find('.scrolling img').width(); /* Find out how many images there are. */ var testimg = $(this).find('.scrolling img').length; /* Do the maths. */ var final = (test* testimg)*1.2; /* Apply the maths to the CSS. */ $(this).find('scrolling').width(final); }); 

在这里,您使用类目标遍历所有div,然后进行计算。 在此循环中,您只需使用$(this)来指示当前选定的

标记。

.each()怎么样?

http://api.jquery.com/each/

就像我们提到scrolling类一样

 $( ".scrolling" ).each( function(){ var img = $( "img", this ); $(this).width( img.width() * img.length * 1.2 ) })