jQuery 这是偶数还是奇数元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7679446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:09:35  来源:igfitidea点击:

Is this an even or odd element?

jqueryjquery-selectors

提问by mrtsherman

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

所以我刚才在 SO 上看到了这个问题,这让我开始思考。

Basically the OP had something along these lines

基本上 OP 有一些类似的东西

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

有没有办法在里面.each()判断你当前的元素是奇数还是偶数?

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

.filterjQuery的方法,但是只有一个元素的时候总是返回true。

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.

我也意识到您可以使用 nth-child 选择器或以其他方式设置它,但我对这种特定情况很好奇。

回答by Sean Vieira

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

回调.each传递给元素的索引和元素:

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

回答by Shef

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

回答by Dennis

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 indexfunction which will calculate the index of the element among its siblings.

否则,使用index函数计算元素在其兄弟元素中的索引。

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

回答by H?c Huy?n Minh

Using Jquery api .is( selector )

使用 Jquery api .is( 选择器 )

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

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

});