全選:判斷「全選」checkbox的狀態,若是選中則把tbody下全部的checkbox選中,反之css
單選:主要是判斷有沒有全選,若是不是選中狀態就把全選的checkbox狀態設置爲false,若是是選中就拿全部選中狀態下「name=id」的chekbox和全部‘’name=id"的數量去比較,若是同樣表示全選了,設置全選的chekbox爲選中狀態,反之。django
1.css部分,直接搬運的django項目裏面的。this
<table border="2" style="margin: 0 auto;text-align: left;width: 800px"> <thead> <tr> <th><input type="checkbox" name="all">全選</th> <th>id</th> <th>用戶名</th> <th>暱稱</th> <th>郵箱</th> <th>角色</th> <th>操做</th> </tr> </thead> <tbody id="tb"> {% for user in userlist %} <tr> <td><input type="checkbox" name="id" value="{{ user.UserID }}" onclick="userCheck(this)"></td> <td>{{ user.UserID }}</td> <td>{{ user.Username }}</td> <td>{{ user.NickName }}</td> <td>{{ user.Email }}</td> <td>{{ user.Role.RoleName }}</td> <td> <img id="update" src="/static/img/edit-new.png" onclick="getUser({{ user.UserID }})"> <img id="delete" src="/static/img/edit_remove.png" onclick="userdelete({{ user.UserID }})"> </td> </tr> {% endfor %} </tbody> </table>
2.js部分,name和id均可以根據實際修改spa
$(function () { //全選,設置chheckbox name='all' tbody id=tb $("input[name=all]").click(function () { if (this.checked) { $("#tb :checkbox").prop("checked", true); } else { $("#tb :checkbox").prop("checked", false); } }); }); //單選 設置name=id function userCheck(ths) { if (ths.checked == false) { $("input[name=all]:checkbox").prop('checked', false); } else { var count = $("input[name='id']:checkbox:checked").length; if (count == $("input[name='id']:checkbox").length) { $("input[name=all]:checkbox").prop("checked", true); } } }