使用jquery将css类添加到行的特定列

问题描述 投票:0回答:2

我有下表:

enter image description here enter image description here

当用户点击一行的特定列(不包括第一列和第二列,即ID和标题列)时,应突出显示除前两列之外的所有列。

因此,如果我点击ID或标题栏,则不会发生任何事情。否则,如果我点击任何其他列,则应突出显示到结尾的第3列。

我使用以下jquery但它似乎没有做到这一点:

JQuery的:

$('#books tbody').on('click', 'tr  td:not(:first-child) td:not(:second-child)', function () {
      $('tr  td:not(:first-child) td:not(:second-child)').toggleClass('selected');
});

CSS:

.even.selected td {
    background-color: rgb(48, 225, 230);
    !important; /* Add !important to make sure override datables base styles */
}

.odd.selected td {
    background-color: rgb(48, 225, 230);
    !important; /* Add !important to make sure override datables base styles */
}

非常感谢您的帮助。

javascript jquery html css
2个回答
2
投票

我为特定代码所做的更改:

  • 您可以在Jquery中使用use the :even or :odd选择器来确定和应用相应的类,而不是将行定义为偶数和奇数。
  • 我们正在利用td:nth-child(n+3)来确定切换类的功能只会在td isn't the 1st or the 2nd one时运行。
  • 适当地,我们检查所选td的父(tr)是奇数还是偶数,并将相应的类存储在selected变量中。
  • 然后我们toggle the classcurrent selected td's parent上的first and second td won't have the class applied

var selected;
$("#books tbody tr td:nth-child(n+3)").click(function() {
  if ($(this).parent().is(":even"))
    selected = "evenrow";
  else
    selected = "oddrow"
  $(this).parent().children().not('td:eq(0), td:eq(1)').toggleClass(selected);
});
tr {
  cursor: pointer;
}

.evenrow {
  background-color: rgb(48, 225, 230) !important;
}

.oddrow {
  background-color: rgb(255, 225, 230) !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="books" border="1">
  <thead>
    <tr>
      <th>ID</th>
      <th>title</th>
      <th>other</th>
      <th>another</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>A</td>
      <td>$100</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>2</td>
      <td>B</td>
      <td>$200</td>
      <td>$300</td>
    </tr>
    <tr>
      <td>3</td>
      <td>C</td>
      <td>$100</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>4</td>
      <td>D</td>
      <td>$200</td>
      <td>$300</td>
    </tr>
  </tbody>
</table>

0
投票

你几乎就在那里,你的选择器只是一点点

tr  td:not(:first-child) td:not(:second-child)

实际上是在说“td不是td下的第二个孩子,不是tr下的第一个孩子”

我实际上并不相信:second-child也是一个有效的选择器。

尝试将该选择器更改为:

tr td + td + td

+运算符意味着“直接跟随元素” - 所以上面说的“紧跟在td之后的一个td,immediatley跟随td”

© www.soinside.com 2019 - 2024. All rights reserved.