Mr.*_*ien 24 checkbox jquery html-table
因为我之前没有找到任何问题,关于如何在点击表格行时切换复选框,所以我想分享我的方法...
Mr.*_*ien 80
为了选择表格中一行的复选框,我们将首先检查type attribute我们所针对的元素是否不是一个复选框,如果它不是一个checbox,我们将检查嵌套在该表格行内的所有复选框.
$(document).ready(function() {
$('.record_table tr').click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
Run Code Online (Sandbox Code Playgroud)
如果你想突出显示表格行,checkbox checked我们可以使用if条件is(":checked"),如果是,我们找到最接近的tr元素使用,.closest()而不是我们使用它添加类addClass()
$("input[type='checkbox']").change(function (e) {
if ($(this).is(":checked")) { //If the checkbox is checked
$(this).closest('tr').addClass("highlight_row");
//Add class on checkbox checked
} else {
$(this).closest('tr').removeClass("highlight_row");
//Remove class on checkbox uncheck
}
});
Run Code Online (Sandbox Code Playgroud)
这个问题对我很有用,但我之前的解决方案存在问题.如果单击表格单元格中的链接,则会触发复选框切换.我用Google搜索了这个,我看到了一个event.stopPropagation()在表格的链接上添加一个命题的命题,如下所示:
$('.record_table tr a').click(function(event) {
event.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)
这个解决方案是一个坏主意,因为我在表的链接上有一些jquery bootstrap popover ...
所以这里有一个更适合我的解决方案.顺便说一下,当我使用bootstrap 2.3时,该行的亮点是通过将"info"类添加到tr.要使用此代码,只需添加class="selectable"到表标记即可.
$(".selectable tbody tr input[type=checkbox]").change(function(e){
if (e.target.checked)
$(this).closest("tr").addClass("info");
else
$(this).closest("tr").removeClass("info");
});
$(".selectable tbody tr").click(function(e){
if (e.target.type != 'checkbox' && e.target.tagName != 'A'){
var cb = $(this).find("input[type=checkbox]");
cb.trigger('click');
}
});
Run Code Online (Sandbox Code Playgroud)
您可能希望更具体地了解测试条件,例如,如果您在行中有其他输入.
像上面提供的许多解决方案一样触发点击将导致该功能运行两次。改为更新 prop 值:
$('tr').click(function(event){
alert('function runs twice');
if(event.target.type !== 'checkbox'){
//$(':checkbox', this).trigger('click');
// Change property instead
$(':checkbox', this).prop('checked', true);
}
});
Run Code Online (Sandbox Code Playgroud)