:nth-of-type() in jQuery / Sizzle?

别等时光非礼了梦想. 提交于 2019-11-27 04:38:32
/**
 * Return true to include current element
 * Return false to exclude current element
 */
$.expr[':']['nth-of-type'] = function(elem, i, match) {
    if (match[3].indexOf("n") === -1) return i + 1 == match[3];
    var parts = match[3].split("+");
    return (i + 1 - (parts[1] || 0)) % parseInt(parts[0], 10) === 0;
};

Test case - (check in IE or rename the selector)

You can of course add even & odd too:

match[3] = match[3] == "even" ? "2n" : match[3] == "odd" ? "2n+1" : match[3];

the jQuery plugin moreSelectors has support for nth-of-type (and many other selectors). I suggest either using that, or simply implement a simple plugin that only implements the exact selectors you need. You should be able to copy-paste code from there.

Happy hacking!

James Wiseman

I can't pretend to know how nth-of-type is implemented, but jQuery does provide a mechanism by which you can create your own custom selector.

The following question deals with custom selectors, and may provide a useful insight to you

What useful custom jQuery selectors have you written?

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