2012-01-02 15 views
10

Sono abbastanza sicuro che questa sarà una risposta davvero facile per te, i whites di jQuery, e sono anche abbastanza simile ad un loop di qualche tipo.jQuery Ciclo attraverso ogni div

Sto cercando di eseguire essenzialmente lo stesso calcolo su due div separate, ma assegnando un valore di larghezza CSS diverso a ciascun ID in base al numero di immagini trovate. I calcoli che sto eseguendo sono irrilevanti per il mio problema, ma li inserisco comunque perché è il codice con cui sto lavorando.

Ecco il markup ...

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

Qui di seguito è il mio attuale jQuery, che funziona bene, ma è inefficiente perché devo scrivere un altro pezzo di codice per ogni div aggiunto. Come posso standardizzare questo in modo che passi attraverso ogni div con la classe di target? Grazie

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

io non sono sicuro che bisogno di fare questo calcolo. Hai provato a risolverlo con puro CSS? – Stefan

risposta

35

Così:

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

La $(this) riferisce alla corrente .target che verrà a passare. All'interno di questo .target sto cercando il .scrolling img e ottenere la larghezza. E poi andare avanti ...

immagini con diverse larghezze

Se si vuole calcolare la larghezza di tutte le immagini (quando hanno larghezze diverse) si può fare in questo modo:

// 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 ")' restituisce una collezione di elementi abbinati. – Stefan

+0

Vero, ma lo starter ha detto che il suo codice funziona, e al momento ho solo aggiunto il ciclo, quindi dovrebbe essere ancora funzionante.Quindi jQuery sceglierà solo il primo IMG che può trovare e restituisce quella larghezza. – Niels

+1

@Stefan, sì, lo fa. Ma 'width()' restituisce solo la larghezza dell'elemento * first * dalla matrice di elementi corrispondenti. –

1

Hai ragione che si tratta di un ciclo, ma questo è, almeno, reso semplice con l'uso del metodo 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)); 

    }); 

Riferimenti:

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

Qui ciclo attraverso tutti i vostri div con classe bersaglio e fate i calcoli. All'interno di questo ciclo puoi semplicemente utilizzare $(this) per indicare il tag <div> attualmente selezionato.

0

Così come ci riferiamo a scrolling classe

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