我使用此功能使我的表格行可点击
$("#grid tbody tr").click(function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
它工作正常,但是当我尝试单击复选框自身时,它不起作用。我应该怎么做才能使它们都起作用?
使用单个事件处理程序:
$("#grid tbody tr").click(function(e) {
if (e.target.type == "checkbox") {
// stop the bubbling to prevent firing the row's click event
e.stopPropagation();
} else {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.attr('checked'));
}
});
$('#grid tbody tr input:checkbox').click(function(e) {
e.stopPropagation();
});
然后单击该复选框将不会触发 tr 上的单击事件。
更好的是你可以用简单的 HTML 来做到这一点,把 for
属性写在label
<input type="checkbox" id="myCheck"><label for="myCheck">CheckThis</label>
^ ^
注意:id
of<input type="checkbox"
将是for
属性的值<label>
尝试这个
$('#grid tbody tr input:checked').click(function(e) {
e.stopPropagation();
});
这些答案都很好,但我被困了很长时间,试图弄清楚为什么我不能让它们工作。我正在动态生成我的表格行,但它们在 DOM 上还不存在。出于这个原因,没有一个解决方案奏效。
为我解决这个问题的是使用on()方法。
$('body').on('click', '#grid tbody tr', function (e) {