editable.js 基于jquery的表格的编辑插件

2020-05-18 09:00:27易采站长站整理

我的思路是这样的:
1.对任何一个 table, tr 都可以添加编辑、删除功能——功能独立
2.可以自动的完成编辑、取消功能,如点击编辑, 表格内容自动变成编辑框、下拉框等, 点击取消结束编辑状态
3.添加删除、确定(即更新)事件——只需要添加自己服务端的删除、更新代码就可以
4.能够自定义设置可编辑列,不可编辑列——方便定制编辑功能
下面是我实现的功能代码:
editable.js

/*
code: editable.js
version: v1.0
date: 2011/10/21
author: lyroge@foxmail.com
usage:
$(“table”).editable({ selector 可以选择table或者tr
head: true, 是否有标题
noeditcol: [1, 0], 哪些列不能编辑
编辑列配置:colindex:列索引
edittype:编辑时显示的元素 0:input 1:checkbox 2:select
ctrid:关联元素的id 如edittype=2, 那么需要设置select的元素
css:元素的样式
editcol: [{ colindex: 2, edittype: 2, ctrid: “sel”,css:””}],
onok: function () {
return true; 根据结果返回true or false
},
ondel: function () {
return true; 根据结果返回true or false
}
});
*/
(function ($) {
$.fn.editable = function (options) {
options = options || {};
opt = $.extend({}, $.fn.editable.defaults, options);
trs = [];
$.each(this, function () {
if (this.tagName.toString().toLowerCase() == “table”) {
$(this).find(“tr”).each(function () {
trs.push(this);
});
}
else if (this.tagName.toString().toLowerCase() == “tr”) {
trs.push(this);
}
});
$trs = $(trs);
if ($trs.size() == 0 || (opt.head && $trs.size() == 1))
return false;
var button = “<td><a href=’#’ class='” + opt.editcss + “‘>编辑</a> <a href=’#’ class='” + opt.delcss + “‘>删除</a><a href=’#’ class='” + opt.onokcss + “‘>确定</a> <a href=’#’ class='” + opt.canclcss + “‘>取消</a></td>”;
$trs.each(function (i, tr) {
if (opt.head && i == 0) {
$(tr).append(“<td></td>”);
return true;
}
$(tr).append(button);
});
$trs.find(“.onok, .cancl”).hide();
$trs.find(“.edit”).click(function () {
$tr = $(this).closest(“tr”);
$tds = $tr.find(“td”);
$.each($tds.filter(“:lt(” + ($tds.size() – 1) + “)”), function (i, td) {
if ($.inArray(i, opt.noeditcol) != -1)
return true;
var t = $.trim($(td).text());
if (opt.editcol != undefined) {
$.each(opt.editcol, function (j, obj) {
if (obj.colindex == i) {
css = obj.css ? “class='” + obj.css + “‘” : “”;
if (obj.edittype == undefined || obj.edittype == 0) {