首页 > jquery改变type=radio的状态

jquery改变type=radio的状态

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="js/jquery-1.4.2.min.js"></script>
    <script>
        $(function(){
            $('.radio').toggle(function() {
                 $(this).attr('checked', true);
            }, function() {
                 $(this).attr('checked', false);
            });
        })
    </script>
</head>
<body>
    <input type="radio" class="radio" name="radio">
</body>
</html>

为什么这样写点击radio会没有反应


应该是checkbox


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="jquery.js"></script>
    <script> 
        $(function(){
            var tag=true;
            $('input[name=test]:radio').click(function() {
                if(tag){
                  $(this).attr('checked', true);
                  tag=false;
                }else{
                  $(this).attr('checked',false);
                  tag=true;
                } 
            });
        })

      </script>
</head>
<body>
    <input type="radio" class="radio" name="test">
</body>
</html> 


radio的'checked'是非布尔值属性。。不管属性值是true还是false,声明了checked那就是被选中的状态。你要是想要切换到未被选中状态,直接
$(this).attr('checked',null)
把'checked'去掉就是了。


对于checkbox,尽量不要使用attr了,可以使用prop,可以控制true和false
http://api.jquery.com/prop/
http://api.jquery.com/removeProp/

【热门文章】
【热门文章】