JQuery - 选中 table 中的复选框

JQuery - check checkboxes in table

我正在从数组中填充 table 中的行。每行都有一个复选框,我想根据特定条件对其进行检查。

所以在填充每一行之后,我试图选中该复选框,但使用它似乎并没有选中它:

if(invoices[i].paid == 'yes'){
    $('.filterPaid').prop('checked', false);
}else{
    $('.filterPaid').prop('checked', true);
}

这是代码:

var invoices = {% raw json_encode(invoices) %};
//console.log(invoices);
var addRow = '';
for(var i = 0; i < invoices.length; i++){
    //alert(invoices[i].invoiceDueYear);

    var date = new Date(invoices[i].invoiceDueYear,invoices[i].invoiceDueMonth,invoices[i].invoiceDueDay);
    var d = date.getDate();
    var month = new Array();
    month[0] = "Jan";
    month[1] = "Feb";
    month[2] = "Mar";
    month[3] = "Apr";
    month[4] = "May";
    month[5] = "Jun";
    month[6] = "Jul";
    month[7] = "Aug";
    month[8] = "Sep";
    month[9] = "Oct";
    month[10] = "Nov";
    month[11] = "Dec";
    var m = month[date.getMonth()]; 

    var y = date.getFullYear();

    var inv = pad(invoices[i].invoiceNo,9,3);

    if(invoices[i].currency === 'GB'){
        var currency = '&#163;';
    }else if(invoices[i].currency === 'US'){
        var currency = '&#36;';
    }else{
        var currency = '&#8364;';
    }

    addRow += '<tr><td><input type="checkbox" class="filterPaid" id="invPaid'+i+'" value="outstanding" name="filterTasks[]"></td><td class="invoiceView" value="'+invoices[i].uid+'"><a href="#">' + inv + '</a></td><td>' + invoices[i].creditorName + '</td><td>' + currency + '' + invoices[i].balance + '</td><td>' + d + ' '+ m +' '+y+'</td></tr>';

    if(invoices[i].paid == 'yes'){
        $('.filterPaid').prop('checked', false);
    }else{
        $('.filterPaid').prop('checked', true);
    }
}
$('#invoiceTable tr').first().after(addRow);

为什么在这种情况下不选中复选框?

在您的代码中,当您尝试使用 jQuery 设置复选框的 checked 属性时,复选框只是一个字符串。在循环外 $('#invoiceTable tr').first().after(addRow); 将 HTML 字符串插入到 DOM 中。从那一刻起,字符串被解析为 HTML,您可以使用代码设置它们的属性。我的建议是将 checked 属性插入到您正在构建的 html 字符串中。

addRow += '<tr><td><input type="checkbox" class="filterPaid" id="invPaid'+i+'" value="outstanding" name="filterTasks[]"></td><td class="invoiceView" value="'+invoices[i].uid+'"><a href="#">' + inv + '</a></td><td>' + invoices[i].creditorName + '</td><td>' + currency + '' + invoices[i].balance + '</td><td>' + d + ' '+ m +' '+y+'</td></tr>';

if(invoices[i].paid == 'yes'){
    $('.filterPaid').prop('checked', false);
}else{
    $('.filterPaid').prop('checked', true);

改成这个

var attr = "";
if(invoices[i].paid == 'yes'){
     attr = "checked";
}

addRow += '<tr><td><input '+attr+' type="checkbox" class="filterPaid" id="invPaid'+i+'" value="outstanding" name="filterTasks[]"></td><td class="invoiceView" value="'+invoices[i].uid+'"><a href="#">' + inv + '</a></td><td>' + invoices[i].creditorName + '</td><td>' + currency + '' + invoices[i].balance + '</td><td>' + d + ' '+ m +' '+y+'</td></tr>';