2016-07-01 5 views
0

Ich suche nach eleganter Weise, nur Divs auf der linken Seite zu wählen (grün markiert). Die Anzahl der Elemente ist unbekannt, daher kann ich mich nicht auf .eq() oder eine andere Funktion zum Filtern von Elementen verlassen. Vielen Dank für einen Hinweis.Elegante Weise, HTML-Elemente zu wählen 1,2,5,6 ... mit unbekannter Anzahl von Elementen/

enter image description here

Html:

<div class="row"> 

<div class="col-sm-6"> 
    <div> 
    </div> 
</div> 
<div class="col-sm-6"> 
    <div> 
    </div> 
</div> 
<div class="col-sm-6"> 
    <div> 
    </div> 
</div> 
<div class="col-sm-6"> 
    <div> 
    </div> 
</div> 
<div class="col-sm-6"> 
    <div> 
    </div> 
</div> 
<div class="col-sm-6"> 
    <div> 
    </div> 
</div> 

+0

ist die Anzahl der Elemente pro Reihe bekannt? – Rouz

+2

teilen Sie bitte die HTML, ist es div oder Tabelle mit Zeile und td – brk

+1

Sie können die Anzahl der Elemente pro Zeile berechnen, und jede Änderung Stil (Anzahl Element pro Zeile/2) – Alexis

Antwort

2

Für jedes div ... Wenn seine linke Offset kleiner ist als der dritte ein ...
Es ausgewählt werden muss.

//Find the offset position of the 3rd div 
offset3 = $(".col-sm-6").eq(2).offset().left; 

$(".col-sm-6").each(function(){ 
    if($(this).offset().left < offset3){ 
     SelectIt = $(this).children("div"); // Select the "green" inner div 

    // Do something with SelectIt... 
    } 
}); 
+0

Cool, das funktioniert für mich. Vielen Dank. – user3573535

0

können Sie first-child & nth-child verwenden. Hope this Snippet wird nützlich sein,

$("#demoTable tr td:first-child").addClass("myClass"); 
$("#demoTable tr td:nth-child(2)").addClass("myClass"); 

JSFIDDLE

Hinweis: Ich habe versucht, mit Tabelle können Sie überprüfen, mit div.row

1

starten:

//Select the first 2 elements of each row 
var rowSize = 4; 
$("div.col-sm-6").filter(function() { 
    return $(this).index() % rowSize < 2; 
}); 

Demo:

$("div.col-sm-6").filter(function() { 
 
\t return $(this).index() % 4 < 2 
 
}).addClass('selected');
.selected { 
 
    background-color:green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="row"> 
 

 
<div class="col-sm-6"> 
 
    <div>1 
 
    </div> 
 
</div> 
 
<div class="col-sm-6"> 
 
    <div>2 
 
    </div> 
 
</div> 
 
<div class="col-sm-6"> 
 
    <div>3 
 
    </div> 
 
</div> 
 
<div class="col-sm-6"> 
 
    <div>4 
 
    </div> 
 
</div> 
 
<div class="col-sm-6"> 
 
    <div>5 
 
    </div> 
 
</div> 
 
<div class="col-sm-6"> 
 
    <div>6 
 
    </div> 
 
</div> 
 
<div class="col-sm-6"> 
 
    <div>7 
 
    </div> 
 
</div> 
 
<div class="col-sm-6"> 
 
    <div>8 
 
    </div> 
 
</div>

Verwandte Themen