2012-01-02 21 views
10

Estoy bastante seguro de que esta será una respuesta realmente fácil para ti jQuery zumba, y también soy bastante tal que involucra un bucle de algún tipo.jQuery Loop a través de cada div

Estoy tratando de realizar esencialmente el mismo cálculo en dos divs separados, pero asignando un valor de ancho de CSS diferente para cada id en función del número de imágenes encontradas. Los cálculos que estoy realizando son irrelevantes para mi problema en realidad, pero los incluyo de todos modos porque es el código real con el que estoy trabajando.

Aquí es el margen de beneficio ...

<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> 

A continuación es mi actual jQuery, que funciona bien, pero es ineficiente porque tengo que escribir otro trozo de código para cada div añadió. ¿Cómo puedo estandarizar esto para que se ejecute a través de cada div con la clase de destino? Gracias

/* 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);  
+1

no estoy seguro de que tiene que hacer estos cálculos. ¿Has intentado resolverlo con CSS puro? – Stefan

Respuesta

35

Como esto:

$(".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); 
}); 

El $(this) refiere a la corriente .target que se bucle a través. Dentro de este .target estoy buscando el .scrolling img y obtengo el ancho. Y luego seguir adelante ...

imágenes con diferentes anchos de

Si desea calcular el ancho de todas las imágenes (cuando tienen diferentes anchos) puede hacerlo de esta manera:

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

'$ (this) .find (". Scrolling img ")' devuelve una colección de elementos coincidentes. – Stefan

+0

Cierto, pero el titular dice que su código funciona, y actualmente solo agregué el bucle, por lo que debería seguir funcionando.Entonces, jQuery solo elegirá el primer IMG que pueda encontrar y devolverá ese ancho. – Niels

+1

@Stefan, sí lo hace. Pero 'width()' solo devuelve el ancho del * primer * elemento de la matriz de elementos coincidentes. –

1

Tienes razón que se trata de un bucle, pero esto es, al menos, hecha sencilla mediante el uso del método de 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)); 

    }); 

Referencias:

1
$('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); 
}); 

Aquí bucle a través de todos sus div con la clase de objetivo y haces los cálculos. Dentro de este ciclo, simplemente puede usar $(this) para indicar la etiqueta <div> actualmente seleccionada.

0

Así como nos referimos a scrolling clase

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