这是偶数还是奇数元素? [英] Is this an even or odd element?

查看:61
本文介绍了这是偶数还是奇数元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

基本上,OP遵循这些原则

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

是否可以在.each()内部判断当前元素是奇数还是偶数实例?

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

有jQuery的.filter方法,但是当它具有单个元素时,它总是返回true.

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

我还意识到您可以使用第n个子选择器或以其他方式进行设置,但是我对此特殊情况感到好奇.

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.

推荐答案

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

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

这篇关于这是偶数还是奇数元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆