如何根据类名称选择偶数或奇数元素 [英] How to select even or odd elements based on class name

查看:252
本文介绍了如何根据类名称选择偶数或奇数元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您这样创建html布局

if you create html layout like so

<ul>
     <li class='a'></li>
     <li class='b'></li>
     <li class='a'></li>
     <li class='b'></li>
     <li class='a'></li>
     <li class='b'></li>
     <li class='a'></li>
     <li class='b'></li>
</ul>

并尝试选择像'$('.a:odd')这样的'a'类的奇数元素,您将获得空数组,而如果执行$$('.a:even'),则将获得所有数组四个'a'类的li元素..真的很奇怪..但是我不是mootools的新手,也许我做错了什么..

and try to select odd elements with 'a' class like so $$('.a:odd') you will get empty array, and if you do $$('.a:even') you will get all four li elements with 'a' class.. It really strange.. But im new to mootools, maybe im doing something wrong..

所以我的问题是如何选择带有类的第一个和第三个li元素. 我知道我可以用这样的功能做到这一点

So my question is how to select first and third li elements with a class. I know that i can do it with function like this

$$('.a').filter(function(item,index){return index%2;}

$$('.a').filter(function(item, index) { return index%2; }

但是对于像选择奇数或偶数元素这样的小任务来说,它太复杂了.

but its too complicated for such small task as selecting odd or even elements..

推荐答案

问题是:odd和:even(及其CSS表亲:nth-​​child(odd)和:nth-​​child(even))是指元素作为其父级的子级出现的顺序,而不是具有该特定选择器的子级.

The problem is that :odd and :even (and their CSS cousins :nth-child(odd) and :nth-child(even)) refer to the order in which the elements appear as children of their parent, not as children with that particular selector.

这对我有用(原型,但看起来MooTools具有类似的语法):

This worked for me (Prototype, but it looks like MooTools has similar syntax):

var odd = $$('.a').filter(function(item, index) {
    return index % 2 == 0;
});
var even = $$('.a').filter(function(item, index) {
    return index % 2 == 1;
});

看来您已经在问题中提到了,嘘我在完整阅读之前回答.

it seems you already covered that in the question, boo on me for answering before reading fully.

这篇关于如何根据类名称选择偶数或奇数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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