【发布时间】:2013-08-20 05:59:03
【问题描述】:
因为我之前没有发现任何问题,关于如何在单击表格行时切换复选框,所以我想分享我的方法......
【问题讨论】:
标签: jquery checkbox html-table
因为我之前没有发现任何问题,关于如何在单击表格行时切换复选框,所以我想分享我的方法......
【问题讨论】:
标签: jquery checkbox html-table
为了选中表格内一行的复选框,我们将首先检查我们定位的元素的typeattribute是否不是复选框,如果不是复选框,我们将检查所有复选框嵌套在该表行内。
$(document).ready(function() {
$('.record_table tr').click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
如果您想突出显示checkboxchecked 上的表格行,我们可以使用if 条件和is(":checked"),如果是,我们使用.closest() 找到最接近的tr 元素,然后我们使用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
}
});
【讨论】:
这个问题对我很有用,但我对之前的解决方案有疑问。如果您单击表格单元格中的链接,它将触发复选框切换。
我用谷歌搜索了这个,我看到一个提议在表格的链接上添加event.stopPropagation(),如下所示:
$('.record_table tr a').click(function(event) {
event.stopPropagation();
});
这个解决方案是个坏主意,因为我在表的链接上有一些 jquery bootstrap 弹出窗口...
所以这里有一个更适合我的解决方案。顺便说一句,当我使用 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');
}
});
您可能希望更具体地说明测试条件,例如,如果您在行中有其他输入。
【讨论】:
你可以简单地触发这个点击事件...:)
$(document).ready(function()
{
$("table tr th :checkbox").click(function(event)
{
$('tbody :checkbox').trigger('click');
});
});
或
$(document).ready(function()
{
$("table tr th :checkbox").on('click',function(event)
{
$('tbody :checkbox').trigger('click');
});
});
【讨论】:
像上面提供的许多解决方案一样触发点击会导致函数运行两次。改为更新 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);
}
});
【讨论】:
即使接受了@Mr. Alien answer 效果很好,如果您决定在某个时候使用 jQuery 动态添加新的 <tr> 行,它就不起作用了。
我建议使用事件委托方法,这只是对已接受答案的轻微修改。
代替:
...
$('.record_table tr').click(function(event) {
...
使用
...
$('.record_table').on('click', 'tr', function(event) {
...
高亮也是一样,使用:
...
$(".record_table").on('change', "input[type='checkbox']", function (e) {
...
更多信息在这里:Click event doesn't fire for table rows added dynamically
【讨论】: