我被要求将表格行单击上的复选框标记为选中,下面的脚本正在工作,但现在当我直接单击复选框时,它不起作用,只有当我单击表格行时才起作用。
我有这个html:
<tr class="linha_tela" id="4">
<td>Profile</td>
<td>Clientes</td>
<td>
<input type="checkbox" checked="checked" id="controller_4" name="controllers[]" value="4" />
</td>
</tr>
这是我的脚本:
$('.linha_tela').click(function(){
var checkbox = $(this).find(':checkbox');
checkbox.attr('checked', !checkbox.attr('checked'));
});
谢谢
最佳答案
发生的情况是,当您单击复选框时,该复选框会切换,然后触发事件处理程序,导致其变为未选中状态。这基本上是瞬时发生的,这就是为什么它看起来根本不起作用。
试试这个:
$('.linha_tela').click(function(event) {
if (!$(event.target).is(':checkbox')) {
var checkbox = $(this).find(':checkbox');
checkbox.attr('checked', !checkbox.attr('checked'));
}
});
编辑:这是一个 jsfiddle demo它的工作原理。
关于javascript - 使用脚本之前复选框不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112597/