项目中经常遇到checked选中的问题,可以通过 JS 或者 jQuery 实现。
1、JS 方法
判断选中:varcheck=document.getElementsByTagName('input')[0];console.log(check.checked);//false
因为HTML代码中没有设置checked属性值,所以默认返回false,反之则返回true。
若要在HTML中设置checkbox为选中状态则可以这样设置:
设置/取消选中://设置元素为选中状态check.checked=true;//设置元素为未选中状态check.checked=false;
2、jQuery 方法
判断选中:
(1)、JQ1.6版本之前(不包括1.6版本)判断checkbox是否被选中用的是attr()方法,HTML代码与上面相同,只放 jQuery 代码:console.log($("input[type='checkbox']").attr('checked'));//false
不要想着在JQ1.6版本之前使用prop()方法,只会报出$().prop()is not a function的错误
(2)、JQ1.6版本之后Jquery中新引入了prop()方法,此时再用attr()方法判断checkbox的状态则会返回undefined,若有设置checked属性为true,则会返回checked而不是true。
1.6+版本 prop() 方法:console.log($("input[type='checkbox']").prop('checked'));//false
(3)、除了以上两种方法JQ中还有一个is()方法同样可以判断checkbox的状态
is() 方法代码如下:console.log($("input[type='checkbox']").is(':checked'));//false
要特别注意不要漏巧":disabled"中的"":"
设置选中:$("input[name='checkbox']").attr("checked",true);
取消选中:$("input[name='checkbox']").attr("checked",false);
注意:true 和 false 是布尔值,不需要加引号。