Home > Article > Web Front-end > jquery :nth-child selector problem solving
I can style each 4th 'item' div.
jQuery(“。item:nth-child “).addClass(”fourth-item“);
and works fine, but I hide some items and show some others, with this style, but only every 4 items are visible. So I have a function that will remove this style and reapply it, but I need the style to be reapplied so it's only every 4th visible item, not every 4th project. I know about the ":visible" selector but can't see linking it with the n subselector correctly, any ideas?
I've tried various things, to no avail...
jQuery(“。item”)。removeClass(“fourth-item”); jQuery(“。item:visible:nth-child(4n)”)。addClass(“fourth-item”);
Solution
: nth-child scans the parent's children, regardless of their styles What is it. The :nth-child is relative to the parent element, not the previous selector. This is explained in the jQeury documentation: nth-child :
code>:nth-child(n), all children are counted regardless of what they are, and the specified element is only counted if it is appended with It is selected only when the selector of pseudo-class matches.
Use a simpler method, each / p>
$('#test li:visible')。each(function(i){ if(i%4 == 0)$(this).addClass('fourth-item'); });
The above is the detailed content of jquery :nth-child selector problem solving. For more information, please follow other related articles on the PHP Chinese website!