问题
How do I add odd/even class only for table rows which haven´t had odd/even class yet? (for some tables I use PHP cycle function).
Is this correct?
$("table tbody tr td")
.parent("tr:nth-child(odd):not(.odd)")
.addClass("odd")
.end()
.parent("tr:nth-child(even):not(.even)")
.addClass("even");
回答1:
jQuery will not duplicate the class if it has already been defined. You can of course always check using .hasClass()
but it is not necessary in this scenario.
Try:
$("table tbody tr:nth-child(odd)").addClass("odd");
$("table tbody tr:nth-child(even)").addClass("even");
[Edit]: From your question is seems that some, but not all, rows have the "odd" or "even" classes already added to them. The safest way is to strip all classes and add them back using JS - $("table tbody tr").removeClass("odd even")
回答2:
Why can not use as follows?
$("table tbody tr:odd").addClass("odd");
$("table tbody tr:even").addClass("even");
来源:https://stackoverflow.com/questions/15387441/how-do-i-add-odd-even-class-only-for-table-rows-which-haven%c2%b4t-had-odd-even-class