jQuery插件_全选反选

灰太狼 2022-05-08 09:52 411阅读 0赞

效果

70

代码:

1、jQuery插件的代码(allCheck.js)

  1. //1、定义全选的插件
  2. jQuery.fn.extend({
  3. bindCheck:function($subCheckBox,$btnUncheck){
  4. let $allCheckBox = this;
  5. //1、给全选复选框绑定click事件
  6. //this:是全选复选框(jQuery对象)
  7. this.click(function(){
  8. let isChecked = this.checked;
  9. $subCheckBox.each(function(){
  10. this.checked = isChecked;
  11. });
  12. });
  13. //2、给反选
  14. if(arguments.length==2){
  15. $btnUncheck.click(function(){
  16. $subCheckBox.each(function(){
  17. this.checked = !this.checked;
  18. });
  19. reversCheck();
  20. });
  21. }
  22. //3、给每个选择项的复选框绑定事件
  23. $subCheckBox.click(function(){
  24. reversCheck();
  25. });
  26. function reversCheck(){
  27. //1、判断是否全部的复选框被选中
  28. let isAllChecked = true;
  29. $subCheckBox.each(function(){
  30. if(!this.checked){
  31. isAllChecked = false;
  32. }
  33. });
  34. //2、处理全选复选框
  35. $allCheckBox.attr("checked",isAllChecked);
  36. }
  37. }
  38. });

2、使用插件的代码(html文件):

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. 选择你喜欢的水果:<br/>
  9. <input id="chkAll" type="checkbox" />全选
  10. <input id="btnUnCheck" type="button" value="反选" /> <br/>
  11. <div id="FruitBox">
  12. <input type="checkbox" />苹果<br/>
  13. <input type="checkbox" />香蕉<br/>
  14. <input type="checkbox" />猕猴桃<br/>
  15. <input type="checkbox" /><br/>
  16. <input type="checkbox" />樱桃<br/>
  17. </div>
  18. </body>
  19. </html>
  20. <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
  21. <script type="text/javascript" src="js/allCheck.js"></script>
  22. <script type="text/javascript">
  23. $(function(){
  24. $("#chkAll").bindCheck($("#FruitBox :checkbox"),$("#btnUnCheck"));
  25. });
  26. </script>

发表评论

表情:
评论列表 (有 0 条评论,411人围观)

还没有评论,来说两句吧...

相关阅读