slion
下午写JS验证,有一个需求需要判断 checkbox是否被选择,查阅相关资料后,总结以下4种方法,分享给大家。

<!
DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jQuery 判断checkbox是否被选中 4种方法</title> <script src="jquery-1.8.3.min.js"></script> <script> $(function(){ $(\'#agree\').on(\'click\', function(){ if($("input[type=\'checkbox\']").is(\':checked\')){ // 选中返回true,未选中返回false console.log(\'已选中\'); }else{ console.log(\'未选中\'); } }) $(\'#agree2\').on(\'change\', function(){ // 可以是 onchange ,也可以是 onclick if($(\'#agree2\').attr(\'checked\')){ console.log(\'已选中\'); }else{ console.log(\'未选中\'); } }) $(\'#agree3\').on(\'change\', function(){ if($("#agree3").get(0).checked){ console.log(\'已选中\'); }else{ console.log(\'未选中\'); } }) $(\'#agree4\').on(\'change\', function(){ if($("#agree4").prop(\'checked\')){ console.log(\'已选中\'); }else{ console.log(\'未选中\'); } }) }) </script> </head> <body> <input type="checkbox" name="agree" id="agree"> 同意此协议 <br> <br> <input type="checkbox" name="agree" id="agree2"> 同意此协议2 <br> <br> <input type="checkbox" name="agree" id="agree3"> 同意此协议3 <br> <br> <input type="checkbox" name="agree" id="agree4"> 同意此协议4 <br> <br> </body> </html>

 

分类:

技术点:

相关文章: