I’m trying to implement a pseudo-class (in jQuery 1.8.3). Here’s the code:
(function($) {
$.extend($.expr[':'], {
group: $.expr.createPseudo(function(arg) {
var index = 0;
return function(element) {
index += 1;
var num = parseInt(arg, 10);
if (isNaN(num)) {
return false;
}
return (((index-1) % (num*2)) < num);
}
})
});
})(jQuery);
The aim of this selector is to apply a style to “n” consecutive groups of elements, and could be used like so to color every 3 rows of a tbody (“this”) in an alternate color (classed with ‘alt’)
$(this).children(':visible').has('td').filter(':group(3)').addClass('alt')
This works well for one tbody. But if I’m iterating on several tbodies (with a ” $(‘..’).each” construct), index is not reset in-between.
This effect could be successfully achieved in jquery 1.6, since we naturally had (in the underlying “group” function parameters) the index within the set:
(function($) {
$.extend($.expr[':'], {
group: function(element, index, matches, set) {
var num = parseInt(matches[3], 10);
if (isNaN(num)) {
return false;
}
return index % (num * 2) < num;
}
});
})(jQuery);
How could we achieve the same effects in jquery 1.8?
Thanks a lot for your insights!
There is a function called
createPositionalPseudoin Sizzle, but it’s not exposed. By duplicating the function, I can actually use it and it worked. I simplified it to just:I create a jsFiddle for test.
I don’t know the inside of Sizzle, it seems
seedis the list of elements for the pseudo filter to process, andmatchesis the list to return, indicating which pass the filter.The
createPositionalPseudoalso modifiesseed, but the code above does not. It could cause problem, since I don’t know what’s inside, I am not sure. However, it runs okay in my test.The JavaScript in the jsFiddle contains a
create_group_pseudo_safe, it’s not simplified. If there is any issue with simplified, that safe version function should work.