返回jQuery实......登陆

jQuery实现CheckBox全选、全不选功能

巴扎黑2017-01-13 13:18:17302
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery实现CheckBox全选、全不选</title>
<script src="http://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>  
<script type="text/javascript">
    $(function() {
    $(':checkbox').click(function(evt){
      // 阻止冒泡
      evt.stopPropagation();
    });
      //判断是否全选
      $("#checkAll").click(function() {
        $('input[name="subBox"]').prop("checked",this.checked); 
      });
      var $subBox = $("input[name='subBox']");
      $subBox.click(function(){
        //alert($subBox.length);
        //alert($("input['subBox']:checked").length);
        $("#checkAll").prop("checked",$subBox.length == $("input[name='subBox']:checked").length ? true : false);
      });
      //用于检查是否选中,选中的话提示值
      $("#butt").click(function (){
        //$('input[name="subBox"]').prop("checked",this.checked); 
        var arrChk=$("input[name='subBox']:checked");
        $(arrChk).each(function(){  //each() 遍历函数
          alert(this.value);            
        }); 
        if(arrChk.length==0){
          alert("没有选中")
        }
      });
    });
  </script>
</head>
<body>
  <div>
    <input id="checkAll" type="checkbox" />全选
    <input name="subBox" type="checkbox" value="1" />选项1
    <input name="subBox" type="checkbox" value="2"/>选项2
    <input name="subBox" type="checkbox" value="3"/>选项3
    <input name="subBox" type="checkbox" value="4"/>选项4
    <input type="button" id="butt" value="检查是否选中"/>
  </div>
</body>
</html>

jQuery版本问题

原本操作属性用的是 $("XXX").attr("attrName");

而jQuery的版本用的是2.1.1,这就是存在一个兼容性和稳定性问题。

jQuery API明确说明,1.6+的jQuery要用prop,尤其是checkBox的checked的属性的判断,

即 使用代码如下:

$("input[name='checkbox']").prop("checked");
$("input[name='checkbox']").prop("disabled", false);
$("input[name='checkbox']").prop("checked", true);

于是乎将attr改为prop,问题得解。

更多关于jQuery实现CheckBox全选、全不选功能请关注PHP中文网(www.php.cn)其他文章!

最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送