在使用dhtmlxGrid插件进行日常开发工作时,避免不了当选中一行或一列等时触发用户自定义的事件处理。这时候就需要你了解dhtmlxGrid是怎样来添加事件处理的。在dhtmlxGrid中可以使用attachEvent和detachEvent方法为dhtmlxGrid添加处理事件。
attachEvent(evName, evHandler) 用来添加用户自定义的事件处理程序到dhtmlxGrid。参数含义如下:
evName 事件名称,如:onRowSelect、onEditCell等
evHandler 用户的定义的事件处理函数
注意:要使用该方法必须导入dhtmlxgrid.js库文件
实例:设置选中表格行时触发的事件(onRowSelect)
grid.attachEvent("onRowSelect", function(rowId,cellIndex){
alert("选中行的ID为" + rowId );
});上面这种形式是采用了直接使用匿名函数的方式进行处理事件,这也是用的最多的的方式。但是,这种方式存在一个缺点,不能够通过detachEvent移除定义的事件处理器。因此,如果想移除事件处理,就使用下面这种方式。
var rowSelectHandler = function(rowId,cellIndex){
alert("选中行的ID为" + rowId );
}
// 注册事件
grid.attachEvent("onRowSelect", rowSelectHandler );
// 移除事件
grid.detachEvent( rowSelectHandler );detachEvent(id) 该方法与attachEvent方法的功能恰好相反,用来从dhtmlxGrid中移除指定的事件处理程序。参数含义如下:
id 事件处理函数的引用。
注意:要使用该方法必须导入dhtmlxgrid.js库文件。
一个具体的实例
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>dhtmlxGrid测试</title>
<link type="text/css" rel="stylesheet" href="../../js/dhtmlxGrid/dhtmlxgrid.css" />
<link type="text/css" rel="stylesheet" href="../../js/dhtmlxGrid/skins/dhtmlxgrid_dhx_skyblue.css" />
<script type="text/javascript" src="../../js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="../../js/dhtmlxGrid/dhtmlxcommon.js"></script>
<script type="text/javascript" src="../../js/dhtmlxGrid/dhtmlxgrid.js"></script>
<script type="text/javascript" src="../../js/dhtmlxGrid/dhtmlxgridcell.js"></script>
</head>
<body>
<div id="gridbox" style="width:600px;height:200px"></div><br/>
<button id="add">添加数据</button>
<script type="text/javascript">
$(function(){
var index = 0;
var mygrid = new dhtmlXGridObject('gridbox');
mygrid.setImagePath("../../js/dhtmlxGrid/imgs/");
mygrid.setHeader("编号,姓名,性别,年龄,联系电话");
mygrid.setInitWidths("80,150,80,80,*");
mygrid.setColAlign("center,left,left,left,left");
mygrid.setColTypes("ro,ro,ro,ro,ro");
mygrid.enableTooltips("true,false,false,false,false");
mygrid.init();
mygrid.setSkin("dhx_skyblue");
// 设置表格数据
mygrid.addRow(index, ["10" + (index++), "张三", "男", 20, "028-9090960"]);
mygrid.addRow(index, ["10" + (index++), "李四", "男", 24, "028-7892960"]);
mygrid.addRow(index, ["10" + (index++), "王五", "男", 22, "028-3693960"]);
mygrid.addRow(index, ["10" + (index++), "薛强", "女", 23, "028-2896960"]);
// 选中表格数据行触发
mygrid.attachEvent("onRowSelect", function(rowId, cellIndex){
alert("行ID=" + rowId + " 单元格下标=" + cellIndex);
});
// 向表格新增时触发
mygrid.attachEvent("onRowAdded", function(rowId){
alert("行ID=" + rowId);
});
$("#add").click(function(){
mygrid.addRow(index, ["10" + (index++), "薛强", "女", 23, "028-2896960"]);
});
});
</script>
</body>
</html>想你展示怎样在项目中使用attachEvent来监听行(onRowSelect)被选中和新增(onRowAdded)数据事件。更多事件请参考官方API,谢谢支持!!!