最近用到easyui,需要表格内编辑,但是我同一个页面有多个表格,把官方的代码修改了一下,如下:
HTML代码
<table id="dg" class="easyui-datagrid" style="width:100%;height:auto" data-options="singleSelect:true,collapsible:true,method:get,fitColumns:true,onClickCell: onClickCell">
<thead>
<tr>
<th data-options="field:id,width:50,align:center">ID</th>
<th data-options="field:name,width:100,align:center">名称</th>
<th data-options="field:num,width:80,align:center,editor:numberbox">数量</th>
<th data-options="field:msg,width:150,align:center">信息</th>
</tr>
</thead>
</table>
JS代码
<script>
$.extend($.fn.datagrid.methods, {
editCell: function(jq,param){
// console.log(param);// {index: 1, field: "msg"}index 行 field,点击的列
return jq.each(function(){
var opts = $(this).datagrid('options');// 表信息
var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
// console.log(fields);// ["id", "name", "num", "msg"] 列字段
for(var i=0; i<fields.length; i++){
var col = $(this).datagrid('getColumnOption', fields[i]);// 列信息
col.editor1 = col.editor;
if (fields[i] != param.field){
col.editor = null;
}
}
$(this).datagrid('beginEdit', param.index);
for(var i=0; i<fields.length; i++){
var col = $(this).datagrid('getColumnOption', fields[i]);
col.editor = col.editor1;
}
});
}
}); var editIndex = undefined;
function endEditing(obj){
if (editIndex == undefined){return true}
if ($(obj).datagrid('validateRow', editIndex)){
$(obj).datagrid('endEdit', editIndex);
editIndex = undefined;
return true;
} else {
return false;
}
}
function onClickCell(index, field){
if (endEditing(this)){
var obj = $(this);
$(this).datagrid('selectRow', index).datagrid('editCell', {index:index,field:field});
editIndex = index; //获取编辑行
var editors = $(this).datagrid('getEditors', index);
var targetEditor = editors[0];
//绑定change事件并取消可编辑状态
if(targetEditor != undefined)
{
targetEditor.target.textbox({ onChange : function(){
obj.datagrid('selectRow', index).datagrid('endEdit', index);
editIndex = undefined;
}
}) } }
}
</script>