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

后端 未结 3 1489
旧时难觅i
旧时难觅i 2020-11-30 08:46

It surprised me that Sizzle (the selector engine jQuery uses) comes with a built-in :nth-child() selector, but lacks an :nth-of-type() selector.

3条回答
  •  既然无缘
    2020-11-30 09:31

    /**
     * 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];
    

提交回复
热议问题