1. 程式人生 > >點選table中的一行選中checkbox,並改變該行的顏色

點選table中的一行選中checkbox,並改變該行的顏色

首先規定一個選中時的樣式:

.bgRed{
    background-color: #b2dba1;
}

table的程式碼如下:

<table>
    <tr>
        <th><input type="checkbox" id="checkAll"> 序號</th>
        <th>所屬機構</th>
        <th>姓名</th>
        <th>手機號碼</th>
    </tr>
        <td
>
<input type="checkbox" name="_dataCheckBox">1</td> <td>山東</td> <td>張三</td> <td>15689547865</td> </tr> </table>

首先實現全選按鈕功能:

$("#checkAll").click(function () {
    if ($('#checkAll').attr('checked')) {
        $("[name='_dataCheckBox']"
).prop("checked", 'true');//全選 $("[name='_dataCheckBox']").each(function () { $(this).parent().parent().toggleClass("bgRed");//新增選中樣式 }); } else { $("[name='_dataCheckBox']").removeAttr("checked");//取消全選 $("[name='_dataCheckBox']").each(function () { $(this
).parent().parent().toggleClass("bgRed");//取消選中樣式 }); } });

實現點選一行選中checkbox,並改變這一行的樣式:

//除了表頭(第一行)以外所有的行新增click事件.
$("tr").first().nextAll().click(function () {
    //如果沒有某個樣式則加上,否則去除
    $(this).children().toggleClass("bgRed");
    if ($(this).children().hasClass("bgRed")){//如果有某個樣式則表明,這一行已經被選中
        $(this).children().first().children().attr("checked", true);
    } else {                                  //如果沒有被選中
        $(this).children().first().children().attr("checked", false);
    }
});