Single selection and selection all by clicking on the table row

Effect picture

Regardless of three or seven twenty-one, a picture will travel the world, as follows:

Application scenarios

Better user experience, no need to precisely click on the small CheckBox to achieve single selection

html

    <div class="table-box">
        <table>
            <thead>
                <tr class="check-all">
                    <th>
                        <input type="checkbox">
                    </th>
                    <th>标题</th>
                    <th>标题</th>
                    <th>标题</th>
                    <th>标题</th>
                </tr>
            </thead>
            <tbody id="table"></tbody>
        </table>
    </div>

css

    .table-box{width: 500px; height: 800px; margin: 200px auto;}
    table {width: 100%; border-collapse: collapse;}
    table td, table th{text-align: center; padding: 10px 0;}
    tr:hover{background: lightblue; cursor: pointer;}

js

let table = $('#table');

for (let i = 0; i < 5; i++) {   //循环插入tr
    let tr = $('<tr></tr>');
    tr.append('<td><input type="checkbox"></td>');
    for (let j = 0; j < 4; j++) {   //循环插入td
        tr.append('<td>内容</td>')
    }
    table.append(tr);
}

$('.check-all').click(function() {

    let checkall = $(this).find('input');
    let checkBtn = $('#table').find('input');

    if (checkall[0].checked) {      //判断全选按钮的 checked 值,点击 tr 改变它的 checked
        checkall.prop('checked', false);
    } else {
        checkall.prop('checked', true);
    }

    checkBtn.prop('checked', checkall[0].checked);      //将单选按钮的 checked 值设为全选按钮的 checked 值
})

$('#table').on('click', 'tr', function() {
    let inputChild = $(this).find('input');

    let len = $(this).parents('#table').find('input').length;   //按钮总长度

    if (inputChild[0].checked) {    //判断每一行按钮的 checked 值,点击该行改变它的 checked
        inputChild.prop('checked', false);
    } else {
        inputChild.prop('checked', true);
    }

    let inputCheckAll = $(this).parents('#table').find('input:checked').length;     //获取选中的按钮长度(ps:放在此处,确保获取的选中个数是对的)

    if (inputCheckAll === len) {    //判断 选中的按钮长度 是否等于 按钮总长度,选中全选按钮
        $('.check-all').find('input').prop('checked', true);
    } else {
        $('.check-all').find('input').prop('checked', false);
    }
    console.log(inputCheckAll);
    console.log(len);
})

end

The realization principle is not explained too much, the comments in js are very clear.

Guess you like

Origin blog.csdn.net/dizuncainiao/article/details/81355908