简体   繁体   中英

Check if element is first or third in rows of 3 elements in jquery

If i have multiple rows of DIVs and each row has 3 elements, how to check if the element is the first in the row or the third in the row? For example:

<div>1</div> <div>2</div> <div>3</div>
<div>4</div> <div>5</div> <div>6</div>
<div>7</div> <div>8</div> <div>9</div>
<div>10</div> <div>11</div> <div>12</div>

So how to check if element is 1,4,7,10 or if it is 3,6,9,12 using jquery or javascript?

Thanks

Using container's class=".cont", the following will alert "First or Third" on div click:

$('.cont div').click(function(){
    var divIndex = $(this).index('.cont div');
    if(((divIndex % 3) == 2) || ((divIndex % 3) == 0))
        alert('First or Third');
});

Use modulo:

http://jsfiddle.net/fQdHk/1/

(function () {
    var n = 3;
    $('div').each(function (i) {
        if(i % n === 0) $(this).css({clear:'left'});
    });
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM