下面小编就为大家带来一篇利用 jQuery 实现 CheckBox 全选 / 全不选 / 反选的简单代码。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
jQuery 是一个兼容多浏览器的 javascript 框架,核心理念是 write less,do more(写得更少, 做得更多)。jQuery 在 2006 年 1 月由美国人 John Resig 在纽约的 barcamp 发布,吸引了来自世界各地的众多 JavaScript 高手加入,由 Dave Methvin 率领团队进行开发。
jQuery 有些版本中实现 CheckBox 全选 / 全不选 / 反选会有 bug,经测试 jquery-1.3.1.js–> 测试通过,jquery-1.5.1.js–> 测试不通过。
实现 CheckBox 全选 / 全不选 / 反选代码如下:
- <%@ page language="java" pageEncoding="UTF-8" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>
- 复选框全选/全不选/反选
- </title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.3.1.js">
- </script>
- <script type="text/javascript">
- /**
- * 全选
- *
- * items 复选框的name
- */
- function allCkb(items) {
- $('[name=' + items + ']:checkbox').attr("checked", true);
- }
- /**
- * 全不选
- *
- */
- function unAllCkb() {
- $('[type=checkbox]:checkbox').attr('checked', false);
- }
- /**
- * 反选
- *
- * items 复选框的name
- */
- function inverseCkb(items) {
- $('[name=' + items + ']:checkbox').each(function() {
- //此处用jq写法颇显啰嗦。体现不出JQ飘逸的感觉。
- //$(this).attr("checked", !$(this).attr("checked"));
- //直接使用js原生代码,简单实用
- this.checked = !this.checked;
- });
- }
- </script>
- </head>
- <body>
- <input type='checkbox' name='ckb' value="0" />
- 白羊座
- <input type='checkbox' name='ckb' value="1" />
- 狮子座
- <input type='checkbox' name='ckb' value="2" />
- 水瓶座
- <input type='checkbox' name='ckb' value="3" />
- 射手座
- <br/>
- <input type="button" onclick="allCkb('ckb')" value="全选" />
- <input type="button" onclick="unAllCkb()" value="全不选" />
- <input type="button" onclick="inverseCkb('ckb')" value="反选" />
- </body>
- </html>
以上这篇利用 jQuery 实现 CheckBox 全选 / 全不选 / 反选的简单代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持 phperz。
来源: http://www.phperz.com/article/17/0330/265279.html