全选,反选,全不选

本文介绍了如何使用JavaScript实现网页元素的全选、反选和不选功能,包括全选按钮、反选按钮和全不选按钮的实现原理和代码解析。

 

 

<!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>

    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">

        $(function () {

            //一:全选功能
            $("#selAll").click(function () {
                $("#playlist :checkbox").attr("checked", true); //#playlist :checkbox中间的空格不能省略
            });
            //二:全不选功能
            $("#unselAll").click(function () {
                $("#playlist :checkbox").attr("checked", false); //就好像使用js中的通过attribute方法来设置一个属性一样
            });

            //三:反选功能
            $("#reverse").click(function () {

                //alert($("#playlist :checkbox").attr("checked")); //取到的始终都是第一个选中的值
                //$("#playlist :checkbox").attr("cecked",!$("#playlist :checkbox").attr("checked"));//不可以,要理解迭代的工作过程

                $("#playlist :checkbox").each(function () {
                    $(this).attr("checked", !$(this).attr("checked"))//选中状态是这个选中状态的相反
                });

                //下面是错误的写法,没有想的这么简单
                //$("#playlist:checkbox").attr("checked", false);

            });

        })
  
    </script>


</head>
<body>


<div id="playlist">

<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 />

</div>

<input type="button" value="全选" id="selAll" />
<input type="button" value="反选" id="reverse" />
<input type="button" value="全不选" id="unselAll" />

</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值