jQuery addClass表问题

时间:2014-04-10 20:05:25

标签: javascript jquery html css whitespace

我有一个使用datatables jQuery插件的表。

我有以下css使最后一列适合文本:

#products tr td:last-child {
  width: 1%;
  white-space: nowrap;
}

这完美无缺。但是,我尝试在最后两列中执行此操作,并且为了跨浏览器,我尝试在jQuery中复制该功能。

我有以下内容:

.fitTableLinks{
  width:1%;
  white-space:nowrap;
}

,jQuery是:

$("#products tr td:last-child").addClass("fitTableLinks");

但这不起作用,但是没有任何控制台错误?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我同意CSS可能是上面Salman A所提到的最好的处理方法。如果你想使用jQuery我认为你必须为每个tr运行你的代码。

$("#products tr").each(function() {
    var $this = $(this);
    $this.find('td:last-child').addClass("fitTableLinks");
});

如果你想要最后两列,只需检查$ this.children()的长度

$("#products tr").each(function() {
    var $this = $(this);
    var secondToLast = $this.children().length - 2;
    $this.find('td:last-child').addClass("fitTableLinks");
    $this.find('td').eq(secondToLast).addClass("fitTableLinks");
});