在实际开发中全选操作会经常用到,这里简单的写了个Jquery的全选插件,方便以后直接调用
/* * jQuery lightweight plugin CheckAll * Original author: Suifengshiqu * Further changes, comments: lvbo1988@gmail.com */ /* 表格全选插件 */ /* 使用方法 */ /* $("#tab").CheckAll({ valueField: "txtTest",attrName: "Id", chkId: "chkall", splitExp: "|", valueIndex: 0 }); */ (function ($) { $.fn.extend({ CheckAll: function (options) { var defaults = { valueField: null, //默认选中后的赋值字段 chkId: "c_all", //全选框的Id attrName: "id", //取值属性 splitExp: "_", //字段分隔符号 valueIndex: 1 //分割后取值的索引下标 }; var options = $.extend(defaults, options); var obj = $(this); //默认为table function _getSelectedValue() { var values = ""; obj.find(":checked").each(function () { //排除下拉菜单中的选中项和全选框 if (!$(this).is("option") && $(this).attr("id") != options.chkId) { values += $(this).attr(options.attrName).split(options.splitExp)[options.valueIndex] + ","; } }); if (values.length > 0) return values.substring(0, values.length - 1); return values; } return this.each(function () { if (obj.is("table")) { var subExp = "#" + obj.attr("Id") + " :checkbox"; var chks = $(subExp + ":gt(0)"); var checkedCount = 0; chks.each(function () { $(this).click(function () { if ($(this).attr("checked")) { checkedCount += 1; } else { checkedCount -= 1; } if (checkedCount < chks.length) { $("#" + options.chkId).attr("checked", false); } else { $("#" + options.chkId).attr("checked", true); } $("#" + options.valueField).val(_getSelectedValue()); }); }); $("#" + options.chkId).click(function () { if ($(this).attr("checked")) { $(subExp).attr("checked", true); checkedCount = chks.length; } else { $(subExp).attr("checked", false); checkedCount = 0; } $("#" + options.valueField).val(_getSelectedValue()); }); } }); } }); })(jQuery);
页面调用如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script src="Scripts/jquery.CheckAll.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("#tab").CheckAll({ valueField: "txtTest" }); }); </script> </head> <body> <table id="tab"> <tr> <td><input type="checkbox" id="c_all" /></td> </tr> <tr> <td><input type="checkbox" id="c_1" /></td> </tr> <tr> <td><input type="checkbox" id="c_2" /></td> </tr> <tr> <td><input type="checkbox" id="c_3" /></td> </tr> <tr> <td><input type="checkbox" id="c_4" /></td> </tr> </table> <input type="text" id="txtTest" /> <span onclick="alert(txtTest.value);">查看选中项</span> </body> </html>