Jquery中单选框的bug

在写单选框案例的时候,感觉Juquery有一个bug,且听我娓娓道来。

bug:

    $('#selectAll').click(function(){
        checkbox.attr('checked',true);
    });

当我使用上面的代码时,第一个有效,但是第二次就失效了。这是为什么呢?查了百度,才知道是jquery版本的问题。

在jquery1.9以前,是可以使用checkbox.attr('checked',true);来修改是否选中单选框。
但是在jquery1.9以后,使用checkbox.attr('checked',true);只能修改一次,第二次就没有用了,需要改用checkbox.prop('checked',true/false);来修改是否选中单选框。

修改后的使用方法:

    $('#selectAll').click(function(){
        checkbox.prop('checked',true);
    });

还有,在一般用到js其值为boolean类型(例:checked,selected,readonly,disabled等)时,直接改用prop()方法,反之使用attr()方法。

全选/全不选/反选的案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单选框实例</title>
    <script src="jquery.js"></script>
</head>
<body>
    <div id="checkbox">
        <input type="checkbox" name="" id="">php
        <input type="checkbox" name="" id="">java
        <input type="checkbox" name="" id="">ruby
        <input type="checkbox" name="" id="">python
    </div>
    <input type="button" value="全选" id="selectAll">
    <input type="button" value="全不选" id="selectNone">
    <input type="button" value="反选" id="selectReverse">
</body>
<script>
    var checkbox = $('#checkbox>:checkbox');
    //全选
    $('#selectAll').click(function(){
        checkbox.prop('checked',true);
    });
    //全不选
    $('#selectNone').click(function(){
        checkbox.prop('checked',false);
    });
    //反选
    $('#selectReverse').click(function(){
        checkbox.each(function(){
            $(this).prop('checked',!$(this).prop('checked'));
        });
    });
</script>
</html>

效果图:
这里写图片描述

原文地址:https://www.cnblogs.com/cnsec/p/13407048.html