更改表格单元格的背景颜色并选中复选框

时间:2011-09-26 05:21:51

标签: jquery

我有一张表“漂亮”的表。

每一行旁边都有一个复选框,用于使用表单选择数据。

我希望能够点击单元格并勾选/取消勾选复选框。

我使用

工作
$(document).ready(function () {
  $('.pretty tr').toggle(function() {
      $(this).find(':checkbox').attr('checked', true);  
  }, function() {
      $(this).find(':checkbox').attr('checked', false);
});

});

除此之外,我希望在选中复选框时更改单元格背景颜色,如果取消选中复选框,则取消选择。

我没有运气这样做,有什么想法吗?

我尝试过添加

$(this).addClass('cssclassname');

上面没有运气:(

只编辑一个更新类“漂亮”已经有以下css,这使得表中的数据每行的颜色不同。

当我尝试使用jquery toggleClass函数时,它不会将其应用于现有的CSS吗?

    table.pretty {
  background: whitesmoke;
  border-collapse: collapse;
}
table.pretty th, table.pretty td {
  border: 1px silver solid;
  padding: 0.2em;
}
table.pretty th {
  background: gainsboro;
  text-align: left;
}
table.pretty caption {
  margin-left: inherit;
  margin-right: inherit;
}
table.pretty tr:nth-child(odd)    { background-color:#eee; }
table.pretty tr:nth-child(even)    { background-color:#fff; }

2 个答案:

答案 0 :(得分:1)

请参阅此DEMO

Jquery的替代方法是HERE

让我们检查一下演示HERE。我不确定这是最好的方法

答案 1 :(得分:0)

$(document).ready(function () {
  $('.pretty tr').toggle(function() {
      $(this).find(':checkbox').attr('checked', true);

  }, function() {
      $(this).find(':checkbox').attr('checked', false);
  });
});

$(this).addClass('class');会这样做......

相关问题