摘要:<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>jQuery實(shí)現(xiàn)CheckBox全選、全不選</title> <script src="http://code.jquery.c
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>jQuery實(shí)現(xiàn)CheckBox全選、全不選</title> <script src="http://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $(':checkbox').click(function(evt){ // 阻止冒泡 evt.stopPropagation(); }); //判斷是否全選 $("#checkAll").click(function() { $('input[name="subBox"]').prop("checked",this.checked); }); var $subBox = $("input[name='subBox']"); $subBox.click(function(){ //alert($subBox.length); //alert($("input['subBox']:checked").length); $("#checkAll").prop("checked",$subBox.length == $("input[name='subBox']:checked").length ? true : false); }); //用于檢查是否選中,選中的話提示值 $("#butt").click(function (){ //$('input[name="subBox"]').prop("checked",this.checked); var arrChk=$("input[name='subBox']:checked"); $(arrChk).each(function(){ //each() 遍歷函數(shù) alert(this.value); }); if(arrChk.length==0){ alert("沒有選中") } }); }); </script> </head> <body> <div> <input id="checkAll" type="checkbox" />全選 <input name="subBox" type="checkbox" value="1" />選項(xiàng)1 <input name="subBox" type="checkbox" value="2"/>選項(xiàng)2 <input name="subBox" type="checkbox" value="3"/>選項(xiàng)3 <input name="subBox" type="checkbox" value="4"/>選項(xiàng)4 <input type="button" id="butt" value="檢查是否選中"/> </div> </body> </html>
jQuery版本問題
原本操作屬性用的是 $("XXX").attr("attrName");
而jQuery的版本用的是2.1.1,這就是存在一個(gè)兼容性和穩(wěn)定性問題。
jQuery API明確說明,1.6+的jQuery要用prop,尤其是checkBox的checked的屬性的判斷,
即 使用代碼如下:
$("input[name='checkbox']").prop("checked"); $("input[name='checkbox']").prop("disabled", false); $("input[name='checkbox']").prop("checked", true);
于是乎將attr改為prop,問題得解。
更多關(guān)于jQuery實(shí)現(xiàn)CheckBox全選、全不選功能請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!