最近用到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>