用jQuery实现全选-全不选-反选的功能

临近过年,刚学IT没多久的小白在这里祝大家在新的一年里:新春快乐,月月赚钱,天天开心,时时快乐,分分精彩,秒秒幸福,事事顺利

古人云:学而时习之,不亦说乎.

学习后经常温习所学的知识,也是件令人愉悦的事情.

今日复习JQuery时,想着用它来实现一下选择的功能也是很方便的.

<html>
    <head>
        <meta charset="utf-8" />
        <title>全选/全不选/反选</title>
        <style>
        </style>
    </head>
    <body>
        <input type="checkbox" />政治<br />
        <input type="checkbox" />军事<br />
        <input type="checkbox" />体育<br />
        <input type="checkbox" />新闻<br />
        <input type="checkbox" />娱乐<br />
        <input type="checkbox" />房产<br />
        <input type="checkbox" />美食<br />
        <input type="checkbox" />科技<br />
        <input type="checkbox" />旅游<br />
        <input type="checkbox" />汽车<br />
        <input type="checkbox" />游戏<br />
        <button>全选</button>
        <button>全不选</button>
        <button>反选</button>
    </body>
    <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
    <script>
    
        $(function(){
            $('button:first').click(function(){
                // $(':checkbox').attr('checked', true)
                $(':checkbox').prop('checked', true)
            })
            $('button:eq(1)').click(function(){
                // $(':checkbox').attr('checked', false)
                $(':checkbox').prop('checked', false)
            })
            $('button:last').click(function(){
                // 以匹配到的每个元素作为上下文执行函数
                $(':checkbox').each(function(){
                    // 获取当前的选中状态,然后取反
                    var checked = !$(this).prop('checked')
                    // 重新设置状态
                    $(this).prop('checked', checked)
                })
            })
        })
        
    </script>
</html>

猜你喜欢

转载自www.cnblogs.com/python-1807/p/10337462.html