Is this an even or odd element?

做~自己de王妃 提交于 2020-12-02 02:53:39

问题


So I saw this question a few moments ago on SO and it got me thinking.

Basically the OP had something along these lines

<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
$('div').each( function() {
   //do something different based on whether even or odd div
   if ($(this) == ':even') {}  //invalid markup I know!
   else {}
});

Is there a way to tell inside the .each() whether your current element is an odd or even instance?

There is the .filter method of jQuery, but it always returns true when it has a single element.

I also realize you can use the nth-child selector or set this up in other ways, but I am curious about this specific case.


回答1:


The callback to .each is passed the element's index and the element:

$('div').each(function(i, el) {
   // As a side note, this === el.
   if (i % 2 === 0) { /* we are even */ }
   else { /* we are odd */ }
});



回答2:


$('div').each( function(index) {
   //do something different based on whether even or odd div
   if (index % 2 == 0) {}  // even
   else {} // odd
});



回答3:


If you know that all of the elements are children of the same parent, you can use the index provided by each

$('div').each( function(index) {
    if (index%2 == 0) {}
    else {}
});

otherwise, use the index function which will calculate the index of the element among its siblings.

$('div').each( function() {
    if ($(this).index()%2 == 0) {}
    else {}
});



回答4:


Using Jquery api .is( selector )

$('div').each( function() {
    //Check if element is even
    if ($(this).is(":even")) {
    }

    //Check if element is odd
    if ($(this).is(":odd")) {
    }

});


来源:https://stackoverflow.com/questions/7679446/is-this-an-even-or-odd-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!