1、checkbox
在某些情况下需要在代码里控制checkbox的状态,而不是在单击的时候才触发。jquery的prop()方法比较好用。
$(selector).prop('checked',true);
$(selector).prop('checked',false);
完整checkbox控制代码:
<div> <input type="checkbox" id="checkbox01"><button id="checkbox01btn">切换选中状态</button> </div> <script type="text/javascript"> $('#checkbox01btn').click(function(){ if($('#checkbox01').prop('checked')){ $('#checkbox01').prop('checked',false); }else{ $('#checkbox01').prop('checked',true); } }); </script>
2、radio
radio也是用prop()方法,prop()方法用在checkbox和radio上比attr()方法好用。
$("input[name='sex'][value='1']").prop("checked",true);
完整的radio的控制代码:
<div> <input type="radio" name="sex" value="1"/>男 <br> <input type="radio" name="sex" value="2"/>女 <br> <div> <button id="radioBtn01">男</button> <button id="radioBtn02">女</button> </div> </div> <script type="text/javascript"> $('#radioBtn01').click(function(){ $("input[name='sex'][value='1']").prop("checked",true); }); $('#radioBtn02').click(function(){ $("input[name='sex'][value='2']").prop("checked",true); }); </script>