JQ实现复选框的全选反选不选

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>全选全不选反选</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(function () {
            $("#selAll").click(function () { //":checked"匹配所有的复选框
                $("#div1 :checkbox").prop("checked", true); //"#div1 :checked"之间必须有空格checked是设置选中状态。如果为true则是选中fo否则false为不选中
            });
            $("#unselAll").click(function () {
                $("#div1 :checkbox").prop("checked", false);
            });
            //理解用迭代原理each(function(){})
            $("#reverse").click(function () {
                $("#div1 :checkbox").each(function () {
                    $(this).prop("checked",!$(this).prop("checked")); //!$(this).attr("checked")判断复选框的状态:如果选中则取反
                });
            });
        });

    </script>
</head>
<body>
<div id="div1">
    <input type="checkbox" />歌曲1<br />
    <input type="checkbox" />歌曲2<br />
    <input type="checkbox" />歌曲3<br />
    <input type="checkbox" />歌曲4<br />
    <input type="checkbox" />歌曲5<br />
    <input type="checkbox" />歌曲6<br />
    <input type="checkbox" />歌曲7<br />
    <input type="button" id="selAll" value="全选" />
    <input type="button" id="unselAll" value="全不选" />
    <input type="button" id="reverse" value="反选 " />
</div>



</body>
</html>

补充说明:

jQuery自从1.6+版本之后,对于checkbox、radio的attr("checked", true)这样的操作,已经替换为prop()方法了,具体可以参看1.6+版本之后的API

问题参考:jQuery实现复选框的全选/全不选,反选,提交

原文地址:https://www.cnblogs.com/zxyun/p/4952089.html