Home > Web Front-end > JS Tutorial > jquery :nth-child selector problem solving

jquery :nth-child selector problem solving

黄舟
Release: 2017-06-23 14:08:31
Original
1890 people have browsed it

I can style each 4th 'item' div.

jQuery(“。item:nth-child “).addClass(”fourth-item“);
Copy after login

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”);
Copy after login

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'); 
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template