jquery處理checkbox(復選框)是否被選中
現在如果一個復選框被選中,是用checked=true,checked="checked"也行
要用prop代替attr會更好,雖然在jQuery1.6之前版本的attr()方法能正常使用,但是現在必須使用prop()方法代替
實例代碼:
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>checkbox</title></head><body><input type="button" id="btn1" value="全選"><input type="button" id="btn2" value="取消全選"><input type="button" id="btn3" value="選中所有奇數"><input type="button" id="btn4" value="反選"><input type="button" id="btn5" value="獲得選中的所有值"><input type="checkbox" value="checkbox1"/><input type="checkbox" value="checkbox2"/><input type="checkbox" value="checkbox3"/><input type="checkbox" value="checkbox4"/><input type="checkbox" value="checkbox5"/><script src="js/jquery-3.2.0.min.js"></script><script>$(function(){var checkbox = $("input[type=checkbox]");$("#btn1").on("click",function(){checkbox.prop("checked",true);});$("#btn2").on("click",function(){checkbox.prop("checked",false);});$("#btn3").on("click",function(){$("input[type=checkbox]:even").prop("checked",true);});$("#btn4").on("click",function(){checkbox.each(function(){if($(this).prop("checked")){$(this).prop("checked",false);}else{$(this).prop("checked",true);}});});$("#btn5").on("click",function(){var str = "";$("input[type=checkbox]").each(function(){if($(this).prop("checked")){str += $(this).val() + ",";}});console.log(str);});});</script></body></html>感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選