Jquery全选与反选点击执行一次的解决方案
网络编程 2021-07-04 21:48www.168986.cn编程入门
在做项目时遇到一个bug,checkbox全选与反选功能,只能点击一次,再点就不起作用了,为了解决此问题,我查找了好多资料,狼蚁网站SEO优化把具体解决方案整理分享给大家,需要的朋友可以参考下
代码需求, 使用attr只能执行一次,使用prop则完美实现全选和反选,获取所有选中的项并把选中项的文本组成一个字符串。
解决方案一:
代码如下:
<html> <head> <script src="jquery-1.11.1.min.js" type="text/javascript"></script> </head> <body> <input type="checkbox" name="chk_list[]" value="1" />1 <input type="checkbox" name="chk_list[]" value="2" />2 <input type="checkbox" name="chk_list[]" value="3" />3 <input type="checkbox" name="chk_list[]" value="4" />4 <input type="checkbox" name="chk_all" id="chk_all" />全选/取消全选 <script type="text/javascript"> $("#chk_all").click(function(){ // 使用attr只能执行一次 $("input[name='chk_list[]']").attr("checked", $(this).attr("checked")); // 使用prop则完美实现全选和反选 $("input[name='chk_list[]']").prop("checked", $(this).prop("checked")); // 获取所有选中的项并把选中项的文本组成一个字符串 var str = ''; $($("input[name='chk_list[]']:checked")).each(function(){ str += $(this).next().text() + ','; }); alert(str); }); </script> </body> </html>
总结:
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
参考
解决方案二:
问题描述:
$(".chooseall").click(function(){ if($(".chooseall").attr("checked") == "checked"){ $("input[name='checkbox1']").removeAttr("checked","checked"); console.log(1); }else{ $("input[name='checkbox1']").attr("checked","checked"); console.log(2); } });
上面的这个代码第一次点击和第二次点击,能实现全选和反选功能,但一遍之后就不再起作用,这是什么情况啊
除了第一个checkbox之外,其余的都是ajax动态生成的,跟这个有关系么?console.log每次点击的都能交替输出1和2,但就是中间的代码不能执行。
解决方案:
removeAttr参数只需要一个,removeAttr("checked")
不过建议替换成
$(".chooseall").click(function(){ if($(".chooseall").prop("checked") == true){ $("input[name='checkbox1']").prop("checked", false); console.log(1); }else{ $("input[name='checkbox1']").prop("checked", false); console.log(2); } });
或者更简洁的,
$(".chooseall").click(function(){ var isChecked = $(this).prop("checked"); $("input[name='checkbox1']").prop("checked", isChecked); });
以上是Jquery全选与反选点击执行一次的解决方案,希望对大家有所帮助。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程