jquery - 在 jQuery 中为 eq 大于 3 的奇数列添加一个类

标签 jquery jquery-selectors

如何为 eq 大于 3 的数据表中的奇数列添加类?这是我尝试过的代码,它将类交给了 tr.有什么巧妙的方法来实现它吗?

$('.dataTable tr').each(function() {
console.log($(this))
if ( $(this).children('td:odd') || $(this).children('td:gt(3)') ) {
$(this).addClass('oddColumn');
// how do I access the td element here ??
}
});

最佳答案

您正在寻找这样的东西吗?

$('tr td:nth-child(2n+5)').addClass('c');

示例:http://jsfiddle.net/ambiguous/AQdY8/

请注意,jQuery 的 nth-child 选择器匹配 the CSS version :

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.

这样做的副作用是 indexes from 1 rather than 0与其他 jQuery 选择器一样:

Because jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1.

关于jquery - 在 jQuery 中为 eq 大于 3 的奇数列添加一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6488949/

相关文章:

jquery - 通过ajax手动缓存图像?

全局 $.ajaxSetup() 的 jQuery 异常(exception)可能吗?

javascript - jQuery 选择器 : all but n first in a row

javascript - 带变量的jquery选择器找不到元素

javascript - JQuery 找不到我的元素。为什么?

javascript - Item 上的 Canvas 鼠标移动事件

jquery - 使用 jQuery 遍历无序列表

javascript - jQuery 复选框并选择 - 对值求和并添加到 var

jquery - 高级 jQuery 过滤 jQuery 数组

jQuery 选择器 - 仅当 <option> 未禁用时才获取 <select> 元素