jQuery addClass table issue

jQuery addClass table issue

本文关键字:issue table addClass jQuery      更新时间:2023-09-26

我有一个使用datatablesjQuery插件的表。

我有以下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");

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

谢谢你的帮助!

我同意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");
});