0

我有一个表,我试图在其中使用 jquery 来定位复选框。我想单击单个 td 中的复选框,然后更改该 td 的背景颜色,但我似乎根本无法定位复选框。这是我表的 tr(它有更多的 td,我只为这个错误包括了两个。

<tr class="sources">
  <td><a href="#">Single Life Annuity</a></td>
  <td>
    <div class="left"><input type="checkbox"></div>
    <div class="right">
      <span class="relval">100%</span>
      <span class="benyou">$517.00</span>
      <span class="benben">$0</span>
    </div>
  </td>
  <td>
    <div class="left"><input type="checkbox"></div>
    <div class="right">
      <span class="relval">98%</span>
      <span class="benyou">$2,916.00</span>
      <span class="benben">$0</span>
    </div>
  </td>
</tr>

这是我用来查找复选框的 jquery。我正在使用 console.log 来确保我找到了复选框,但本质上会使用addClass(".active");

 $(".sources td").click(function(e)
 {
   $(this).parent().find('input:checkbox').attr('checked', 'checked');
   console.log('you got it!');
 });

任何帮助都会很棒!提前致谢。

4

4 回答 4

1

使用您的示例(绑定到单击表格单元格),这将选择单元格并为其应用红色背景:

$(this).css('background','red');

jsFiddle 示例

如果您希望绑定到复选框的单击事件,请尝试以下操作:

$(".sources td input").click(function (e) {
    $(this).parent().find('input:checkbox').attr('checked', 'checked');
     $(this).closest('td').css('background','red');
    console.log('you got it!');
});

jsFiddle 示例

于 2013-03-12T20:17:15.080 回答
1
$('input[type="checkbox"]').click(function() {
    if($(this).is(':checked')) {
        $(this).parent().parent().addClass('active');
    } else {
        $(this).parent().parent().removeClass('active');
    }
});
于 2013-03-12T20:19:04.930 回答
0

您也可以尝试使用 .prop() 方法。

 $(this).parent().find('input:checkbox').prop("checked", true);

http://api.jquery.com/prop/

于 2013-03-12T20:24:18.193 回答
0

根据需要:演示

$('input[type="checkbox"]').click(function() {
    if($(this).is(':checked')) {
        $(this).parent().parent().css('background','red');
    } else {
       $(this).parent().parent().css('background','white');
    }
});

其他方式,通过单击中的任意位置来工作<td>DEMO

$(".sources td").click(function (e) {
    if ($(this).find('input:checkbox').is(':checked')) { 
        $(this).find('input:checkbox').attr('checked', false);
        $(this).closest('td').css('background','white');
    }
    else
    {
        $(this).find('input:checkbox').prop('checked', 'checked');
        $(this).closest('td').css('background','red');
    }
});
于 2013-03-12T20:30:45.990 回答