How do I add odd/even class only for table rows which haven´t had odd/even class yet?

半城伤御伤魂 提交于 2019-12-12 03:55:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!