jQuery EasyUI教程之datagrid应用(三)

10 篇文章 0 订阅
3 篇文章 0 订阅

jQuery EasyUI教程之datagrid应用(三)

 

三、设定或定制各种功能

 

1、增加分页



 

创建DataGrid数据表格

 

设置“url”属性,用来装入远端服务器数据,服务器返回JSON格式数据。

<table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
url="datagrid2_getdata.php"
title="Load Data" iconCls="icon-save"
rownumbers="true" pagination="true">
	<thead>
		<tr>
			<th field="itemid" width="80">Item ID</th>
			<th field="productid" width="80">Product ID</th>
			<th field="listprice" width="80" align="right">List Price</th>
			<th field="unitcost" width="80" align="right">Unit Cost</th>
			<th field="attr1" width="150">Attribute</th>
			<th field="status" width="60" align="center">Stauts</th>
		</tr>
	</thead>
</table>

 定义datagrid列,将“pagination”属性设为true,将会在datagrid底部生成一个分页工具条。 pagination会发送两个参数给服务器:

  1、page: 页码,从1开始。

  2、rows: 每页显示行数。


服务器端代码

 

$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
// ...

$rs = mysql_query("select count(*) from item");
$row = mysql_fetch_row($rs);
$result["total"] = $row[0]; 
$rs = mysql_query("select * from item limit $offset,$rows"); 
$items = array();
while($row = mysql_fetch_object($rs)){
	array_push($items, $row);
}

$result["rows"] = $items; 
echo json_encode($result);

 
2、增加搜索

 



 

创建DataGrid


创建一个有分页特性的datagrid,然后增加一个搜索工具条。

<table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
url="datagrid24_getdata.php" toolbar="#tb"
title="Load Data" iconCls="icon-save"
rownumbers="true" pagination="true">
	<thead>
		<tr>
			<th field="itemid" width="80">Item ID</th>
			<th field="productid" width="80">Product ID</th>
			<th field="listprice" width="80" align="right">List Price</th>
			<th field="unitcost" width="80" align="right">Unit Cost</th>
			<th field="attr1" width="150">Attribute</th>
			<th field="status" width="60" align="center">Stauts</th>
		</tr>
	</thead>
</table>

 工具条定义为:

<div id="tb" style="padding:3px">
	<span>Item ID:</span>
	<input id="itemid" style="line-height:26px;border:1px solid #ccc">
	<span>Product ID:</span>
	<input id="productid" style="line-height:26px;border:1px solid #ccc">
	<a href="#" class="easyui-linkbutton" plain="true" οnclick="doSearch()">Search</a>
</div>

 用户输入搜索值,然后点击搜索按钮,“doSearch”函数将会被调用:

function doSearch() {
	$('#tt').datagrid('load', {
		itemid: $('#itemid').val(),
		productid: $('#productid').val()
	});
}

 上面的代码调用“load”方法来装载新的datagrid数据,同时需要传递“itemid”和“productid”参数到服务器。


服务器端代码

include 'conn.php'; 

$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$itemid = isset($_POST['itemid']) ? mysql_real_escape_string($_POST['itemid']) : '';
$productid = isset($_POST['productid']) ? mysql_real_escape_string($_POST['productid']) : ''; 
$offset = ($page-1)*$rows; 

$result = array(); 
$where = "itemid like '$itemid%' and productid like '$productid%'";
$rs = mysql_query("select count(*) from item where " . $where);
$row = mysql_fetch_row($rs);
$result["total"] = $row[0]; 

$rs = mysql_query("select * from item where " . $where . " limit $offset,$rows"); 
$items = array();
while($row = mysql_fetch_object($rs)){
	array_push($items, $row);
}

$result["rows"] = $items; 
echo json_encode($result);

 

3、获取选择行数据

本示例教你如何获取选择行数据。



 

Datagrid组件含有两个方法用来接收选择行数据:

  • getSelected: 获取所选择行的第一行数据,如果没有行被选择返回null,否则返回数据记录。
  • getSelections: 获取所有选择行数据,返回数组数据,里面的数组元素就是数据记录。

创建DataGrid

 

<table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
url="data/datagrid_data.json"
title="Load Data" iconCls="icon-save">
	<thead>
		<tr>
		<th field="itemid" width="80">Item ID</th>
		<th field="productid" width="80">Product ID</th>
		<th field="listprice" width="80" align="right">List Price</th>
		<th field="unitcost" width="80" align="right">Unit Cost</th>
		<th field="attr1" width="150">Attribute</th>
		<th field="status" width="60" align="center">Stauts</th>
		</tr>
	</thead>
</table>

 

实例用法

获取单行数据:

 

   var row = $('#tt').datagrid('getSelected');
   if (row){
       alert('Item ID:'+row.itemid+"\nPrice:"+row.listprice);
   }

 获取所有行itemid:

var ids = [];
var rows = $('#tt').datagrid('getSelections');
for(var i=0; i<rows.length; i++){
    ids.push(rows[i].itemid);
}
alert(ids.join('\n'));

 

4、增加工具条

本示例教你如何增加一个工具条到datagrid中。
 
创建DataGrid


 

 

<table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
url="data/datagrid_data.json"
title="DataGrid with Toolbar" iconCls="icon-save"
toolbar="#tb">
    <thead>
	<tr>
	    <th field="itemid" width="80">Item ID</th>
	    <th field="productid" width="80">Product ID</th>
	    <th field="listprice" width="80" align="right">List Price</th>
	    <th field="unitcost" width="80" align="right">Unit Cost</th>
	    <th field="attr1" width="150">Attribute</th>
	    <th field="status" width="60" align="center">Stauts</th>
	</tr>
    </thead>
</table>

<div id="tb">
    <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" οnclick="javascript:alert('Add')">Add</a>
    <a href="#" class="easyui-linkbutton" iconCls="icon-cut" plain="true" οnclick="javascript:alert('Cut')">Cut</a>
    <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" οnclick="javascript:alert('Save')">Save</a>
</div>

 

5、复杂工具条

datagrid的工具条不仅仅只是包含按钮,还可以是其它的组件。为方便布局,你可以通过现有的构成datagrid工具条的DIV来定义工具条。本教程教你如何创建一个复杂的工具条,作为datagrid的组件。


 
创建Toolbar

 

 

<div id="tb" style="padding:5px;height:auto">
    <div style="margin-bottom:5px">
	<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true"></a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true"></a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true"></a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-cut" plain="true"></a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true"></a>
    </div>
    <div>
	Date From: <input class="easyui-datebox" style="width:80px">
	To: <input class="easyui-datebox" style="width:80px">
	Language: 
	<input class="easyui-combobox" style="width:100px"
	url="data/combobox_data.json"
	valueField="id" textField="text">
	<a href="#" class="easyui-linkbutton" iconCls="icon-search">Search</a>
    </div>
</div>

 

创建DataGrid

 

 

<table class="easyui-datagrid" style="width:600px;height:250px"
url="data/datagrid_data.json" 
title="DataGrid - Complex Toolbar" toolbar="#tb"
singleSelect="true" fitColumns="true">
    <thead>
	<tr>
	    <th field="itemid" width="60">Item ID</th>
	    <th field="productid" width="80">Product ID</th>
	    <th field="listprice" align="right" width="70">List Price</th>
	    <th field="unitcost" align="right" width="70">Unit Cost</th>
	    <th field="attr1" width="200">Address</th>
	    <th field="status" width="50">Status</th>
	</tr>
    </thead>
</table>

 

6、冻结列

本示例演示如何冻结数据列,当用户水平滚动数据表格时,冻结的数据列不会滚动出视图界面外。
 

 
通过定义frozenColumns属性来冻结列,冻结列属性的定义同列属性。

 

$('#tt').datagrid({
    title: 'Frozen Columns',
    iconCls: 'icon-save',
    width: 500,
    height: 250,
    url: 'data/datagrid_data.json',
    frozenColumns: [[{
        field: 'itemid',
        title: 'Item ID',
        width: 80
    },
    {
        field: 'productid',
        title: 'Product ID',
        width: 80
    },
    ]],
    columns: [[{
        field: 'listprice',
        title: 'List Price',
        width: 80,
        align: 'right'
    },
    {
        field: 'unitcost',
        title: 'Unit Cost',
        width: 80,
        align: 'right'
    },
    {
        field: 'attr1',
        title: 'Attribute',
        width: 100
    },
    {
        field: 'status',
        title: 'Status',
        width: 60
    }]]
});

 创建冻结列的datagrid可以不用编写任何javascript代码,如下面这样:

 

<table id="tt" title="Frozen Columns" class="easyui-datagrid" style="width:500px;height:250px"
url="data/datagrid_data.json"
singleSelect="true" iconCls="icon-save">
    <thead frozen="true">
	<tr>
	    <th field="itemid" width="80">Item ID</th>
	    <th field="productid" width="80">Product ID</th>
	    </tr>
	    </thead>
	    <thead>
	    <tr>
	    <th field="listprice" width="80" align="right">List Price</th>
	    <th field="unitcost" width="80" align="right">Unit Cost</th>
	    <th field="attr1" width="150">Attribute</th>
	    <th field="status" width="60" align="center">Stauts</th>
	</tr>
    </thead>
</table>

 

7、格式化数据列

下面为EasyUI DataGrid里的格式化列示例,用一个定制的列格式化器(formatter)来将文本标注为红色,如果价格低于20的话。
 

 
为格式化一个DataGrid列,我们需要设置格式化属性,它是一个函数。格式化函数含有三个参数:

  • value: 当前绑定的列字段值。
  • row: 当前行记录数据。
  • index: 当前行索引。

创建DataGrid

 

 

<table id="tt" title="Formatting Columns" class="easyui-datagrid" style="width:550px;height:250px"
url="data/datagrid_data.json"
singleSelect="true" iconCls="icon-save">
    <thead>
	<tr>
	    <th field="itemid" width="80">Item ID</th>
	    <th field="productid" width="80">Product ID</th>
	    <th field="listprice" width="80" align="right" formatter="formatPrice">List Price</th>
	    <th field="unitcost" width="80" align="right">Unit Cost</th>
	    <th field="attr1" width="100">Attribute</th>
	    <th field="status" width="60" align="center">Stauts</th>
	</tr>
    </thead>
</table>

 注意:“listprice”字段有一个“formatter”属性,用来指明格式化函数。

 

编写格式化函数

 

function formatPrice(val,row){
    if (val < 20){
	return '<span style="color:red;">('+val+')</span>';
    } else {
	return val;
    }
}

 

8、增加排序功能

本示例演示如何通过点击列表头来排序DataGrid数据。
 

 
DataGrid中的全部列都可以排序,可以定义哪一个列进行排序。默认列属性不会进行排序,除非列的排序属性sortable设置为true。

创建DataGrid

<table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
url="datagrid8_getdata.php"
title="Load Data" iconCls="icon-save"
rownumbers="true" pagination="true">
    <thead>
	<tr>
	    <th field="itemid" width="80" sortable="true">Item ID</th>
	    <th field="productid" width="80" sortable="true">Product ID</th>
	    <th field="listprice" width="80" align="right" sortable="true">List Price</th>
	    <th field="unitcost" width="80" align="right" sortable="true">Unit Cost</th>
	    <th field="attr1" width="150">Attribute</th>
	    <th field="status" width="60" align="center">Stauts</th>
	</tr>
	</thead>
</table>

 定义了可排序的列为:itemid、productid、listprice、unitcost等。“attr1”列和“status”列不能排序。
DataGrid的排序会发送两个参数给服务器:

  • sort: 排序列字段名。
  • order: 排序方式,可以是“asc(升序)”或“desc(降序)”,默认为“asc”。

服务器端代码

 

 

$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'itemid';
$order = isset($_POST['order']) ? strval($_POST['order']) : 'asc';
$offset = ($page-1)*$rows;

$result = array(); 

include 'conn.php'; 

$rs = mysql_query("select count(*) from item");
$row = mysql_fetch_row($rs);
$result["total"] = $row[0]; 

$rs = mysql_query("select * from item order by $sort $order limit $offset,$rows"); 
$items = array();
while($row = mysql_fetch_object($rs)){
    array_push($items, $row);
}

$result["rows"] = $items; 
echo json_encode($result);

 

9、增加选择框

本教程教你如何放置一个checkbox 列到 DataGrid中。利用选择框用户可以即刻选择/取消所有表格数据行。
 

 
为增加一个checkbox列,我们只需简单将checkbox属性设置为true即可。代码如下所示:

 

<table id="tt" title="Checkbox Select" class="easyui-datagrid" style="width:550px;height:250px"
url="data/datagrid_data.json"
idField="itemid" pagination="true"
iconCls="icon-save">
    <thead>
	<tr>
	    <th field="ck" checkbox="true"></th>
	    <th field="itemid" width="80">Item ID</th>
	    <th field="productid" width="80">Product ID</th>
	    <th field="listprice" width="80" align="right">List Price</th>
	    <th field="unitcost" width="80" align="right">Unit Cost</th>
	    <th field="attr1" width="100">Attribute</th>
	    <th field="status" width="60" align="center">Status</th>
	</tr>
    </thead>
</table>

 上面的代码增加了一个含有checkbox属性的列,从而生成了一个选择框列。如果idField属性被设置,DataGrid的已选行在不同的页面里都可以维持。

 

10、增强行内编辑

Datagrid最近增加了一个可编辑功能,它使用户可增加新行到datagrid中,用户也可对单行或多行数据进行更新。
本教程教你如何创建一个带有行编辑功能的datagrid。


 
创建DataGrid

 

$(function() {
    $('#tt').datagrid({
        title: 'Editable DataGrid',
        iconCls: 'icon-edit',
        width: 660,
        height: 250,
        singleSelect: true,
        idField: 'itemid',
        url: 'datagrid_data.json',
        columns: [[{
            field: 'itemid',
            title: 'Item ID',
            width: 60
        },
        {
            field: 'productid',
            title: 'Product',
            width: 100,
            formatter: function(value) {
                for (var i = 0; i < products.length; i++) {
                    if (products[i].productid == value) return products[i].name;
                }
                return value;
            },
            editor: {
                type: 'combobox',
                options: {
                    valueField: 'productid',
                    textField: 'name',
                    data: products,
                    required: true
                }
            }
        },
        {
            field: 'listprice',
            title: 'List Price',
            width: 80,
            align: 'right',
            editor: {
                type: 'numberbox',
                options: {
                    precision: 1
                }
            }
        },
        {
            field: 'unitcost',
            title: 'Unit Cost',
            width: 80,
            align: 'right',
            editor: 'numberbox'
        },
        {
            field: 'attr1',
            title: 'Attribute',
            width: 150,
            editor: 'text'
        },
        {
            field: 'status',
            title: 'Status',
            width: 50,
            align: 'center',
            editor: {
                type: 'checkbox',
                options: {
                    on: 'P',
                    off: ''
                }
            }
        },
        {
            field: 'action',
            title: 'Action',
            width: 70,
            align: 'center',
            formatter: function(value, row, index) {
                if (row.editing) {
                    var s = '<a href="#" οnclick="saverow(this)">Save</a> ';
                    var c = '<a href="#" οnclick="cancelrow(this)">Cancel</a>';
                    return s + c;
                } else {
                    var e = '<a href="#" οnclick="editrow(this)">Edit</a> ';
                    var d = '<a href="#" οnclick="deleterow(this)">Delete</a>';
                    return e + d;
                }
            }
        }]],
        onBeforeEdit: function(index, row) {
            row.editing = true;
            updateActions(index);
        },
        onAfterEdit: function(index, row) {
            row.editing = false;
            updateActions(index);
        },
        onCancelEdit: function(index, row) {
            row.editing = false;
            updateActions(index);
        }
    });
});

function updateActions(index) {
    $('#tt').datagrid('updateRow', {
        index: index,
        row: {}
    });
}

 
为了让datagrid可编辑数据,要增加一个editor属性到列属性里,编辑器会告诉datagrid如何编辑字段和如何保存字段值,这里定义了三个editor:text、combobox和checkbox。

 

function getRowIndex(target) {
    var tr = $(target).closest('tr.datagrid-row');
    return parseInt(tr.attr('datagrid-row-index'));
}
function editrow(target) {
    $('#tt').datagrid('beginEdit', getRowIndex(target));
}
function deleterow(target) {
    $.messager.confirm('Confirm', 'Are you sure?',
    function(r) {
        if (r) {
            $('#tt').datagrid('deleteRow', getRowIndex(target));
        }
    });
}
function saverow(target) {
    $('#tt').datagrid('endEdit', getRowIndex(target));
}
function cancelrow(target) {
    $('#tt').datagrid('cancelEdit', getRowIndex(target));
}

 
11、扩展编辑器

一些通用编辑器被加入到datagrid中,用来允许用户编辑数据。所有编辑器在 $.fn.datagrid.defaults.editors对象中进行定义,被扩展来支持新编辑器。本教程教你如何增加一个新的numberspinner编辑器到datagrid中。


 
扩展numberspinner编辑器

 

$.extend($.fn.datagrid.defaults.editors, {
    numberspinner: {
        init: function(container, options) {
            var input = $('<input type="text">').appendTo(container);
            return input.numberspinner(options);
        },
        destroy: function(target) {
            $(target).numberspinner('destroy');
        },
        getValue: function(target) {
            return $(target).numberspinner('getValue');
        },
        setValue: function(target, value) {
            $(target).numberspinner('setValue', value);
        },
        resize: function(target, width) {
            $(target).numberspinner('resize', width);
        }
    }
});

 
在html标识理创建DataGrid

 

<table id="tt" style="width:600px;height:250px"
url="data/datagrid_data.json" title="Editable DataGrid" iconCls="icon-edit"
singleSelect="true" idField="itemid" fitColumns="true">
    <thead>
	<tr>
	    <th field="itemid" width="60">Item ID</th>
	    <th field="listprice" width="80" align="right" editor="{type:'numberbox',options:{precision:1}}">List Price</th>
	    <th field="unitcost" width="80" align="right" editor="numberspinner">Unit Cost</th>
	    <th field="attr1" width="180" editor="text">Attribute</th>
	    <th field="status" width="60" align="center" editor="{type:'checkbox',options:{on:'P',off:''}}">Status</th>
	    <th field="action" width="80" align="center" formatter="formatAction">Action</th>
	</tr>
    </thead>
</table>

 指定numberspinner编辑器到“unit cost”字段,当启动编辑行,用户就可以利用numberspinner编辑器组件来编辑数据。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值