在做项目时遇到一个bug,checkbox全选与反选功能,只能点击一次,再点就不起作用了,为了解决此问题,我查找了好多资料,下面把具体解决方案整理分享给大家,需要的朋友可以参考下:
代码需求, 使用attr只能执行一次,使用prop则完美实现全选和反选,获取所有选中的项并把选中项的文本组成一个字符串。
存在bug的代码:只能全选一次就失效
$(document).ready(function(){ $("#CalculationAll").click(function(){ var ischecked = this.checked; $("form input").each(function(){ if($(this).val()!='CalculationAll') { $(this).attr("checked",ischecked);//每一项都选中 attr ,这个有问题,选中一次下一次就失效 } calculationAll();//计算购物车选中总价格 }); }); }); function calculationAll() { count = 0; $("form input").each(function(){ if($(this).val()!='CalculationAll') {//过滤全选input goodsId = $(this).val(); if(this.checked) { num = parseInt($("#num_"+goodsId).text()); price = parseFloat($("#price_"+goodsId).text()); count = count+(num * price); } } }); $('#count').text(count.toFixed(2)); }
修正后的代码:
$(document).ready(function(){ $("#CalculationAll").click(function(){ var ischecked = this.checked; $("form input").each(function(){ if($(this).val()!='CalculationAll') { $(this).prop("checked",ischecked);//选中或取消选择,做全选用 } calculationAll();//计算选中物品的价格 }); }); });
参考:http://www.jb51.net/article/71067.htm