layui框架使用与代码编写

layui框架使用与代码编写

一、layui增加操作工具列

ShowLeakList = ListPager.extend({
	init : function(container, primaryKey, url){
		//列表容器
		this.container = container;
		//主键字段
		this.primaryKey = primaryKey;
		//数据请求地址
		this.url = url;
		//界面需要引用的插件
		this.plugins = ['table', 'element', 'form', 'laydate', 'layer','carousel'];
//		//弹出卡片界面的大小[60%,80%]
//		this.cardSize = ['100%','100%'];
//		//弹出卡片界面方式:页面层(这里content是一个普通的String):1;iframe层(content是一个URl):2
		this.cardPopStyle = 2;
		//每页大小 
		this.pageSize = 5;
		//列表头
		this.title = [[
			{field: 'checkDate', title: '检测日期', width: 120},
			
			{field: 'startTime', title: '检测开始时间', width: 120},
			
			{field: 'endTime', title: '检测结束时间', width: 120},
			
			{field: 'checkUser', title: '检测人', width: 120},
			
			
			{fixed: 'right', title: '轨迹查看', align:'center',width: 100, toolbar: '#scanLeak'}
			
	     ]]; 
		//插件是基于layui封装的, layOption是对layui的参数扩展(具体api参照layui属性)
		this.layOption = {
				
		};
	},
	initLayuiPlugin: function(){
		this._super();
	},
	initEvent: function(){
		this._super();
		//TODO 父类仅仅绑定了工具条通用按钮事件, 如有其他事件请在这里定义
	},
	hookMethod:function(obj){
		debugger;
	 	var data = obj.data,
	 	url = CONTEXT_PATH + '/cusviews/leak/listLeakPoint';
		var param = {
				checkId : data.checkId
		}
		var retData = $.getData(url,param);
		if(1000 != retData.status){
			layer.msg('获取数据失败', {icon: 5});
			return;
		}
		var points = [];
		var data = retData.data;
		if(!$.isEmptyArray(data)){
			Leak.removePoint();
			for(var i=0;i

layui框架使用与代码编写_第1张图片

layui框架使用与代码编写_第2张图片

      

显示超链接

{field: 'oriLink', title: '原文链接', width: 120,templet: ''},

列表页显示操作按钮

前台

 
this.title = [[{checkbox: true, LAY_CHECKED: false}, {title: '序号', templet: '#indexTpl',width:80}, {field: 'title', title: '资讯名称', width: 120}, {field: 'checkColumnIdName', title: '分类', width: 120}, {field: 'isWorkName', title: '状态', width: 120}, {field: '', title: '操作', width: 150,align:'center', toolbar:'#operation'}, ]]; hookMethod:function(obj){ var _self = this, data = obj.data //获得当前行数据 ,layEvent = obj.event //获得 lay-event 对应的值 ,url = ""; var subjectClassifyId = $("#subjectClassifyId").val(); if(layEvent === 'delNews'){ //url = CONTEXT_PATH + "/subjectClassify/showSubjectClassifyNewsList?act=" + WebConst.EDIT+"&entityId="+data.subjectClassifyId; layer.confirm('您确定要删除该条数据吗?', { btn: ['确定','取消'] //按钮 }, function(){ $.post(CONTEXT_PATH+"/subjectClassify/delCheckAdviceNewsRel",{subjectClassifyId:subjectClassifyId,checkAdviceId:data.checkAdviceId},function(data){ layer.msg('删除成功!', {icon: 1}); window.location.reload(); }); }, function(){ }); /* var layIndex = layer.open({ type: this.cardPopStyle, title: "资讯管理", maxmin: true, shadeClose: true, //开启遮罩关闭 area: ['100%','100%'], content: this.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER ? $.loadHtml(url) : url, success: function(layero){ } });*/ } if(layEvent === 'notNews'){ layer.confirm('您确定要暂停该条数据吗?', { btn: ['确定','取消'] //按钮 }, function(){ $.post(CONTEXT_PATH+"/subjectClassify/checkAdviceNewsNotWork",{checkAdviceId:data.checkAdviceId},function(data){ layer.msg('已暂停!', {icon: 1}); window.location.reload(); }); }, function(){ }); } },

二、layui列表显示图片

layui的列表界面

{field: '', title: '照片', width: 120,templet:'
'},

后台

业务实体类

    private String href;
    private String imgPosition;
    private String imgPositionName;
    private Attach picName;
    private String imagePath = null;


	public Attach getPicName() {
		return picName;
	}
	public void setPicName(Attach picName) {
		this.picName = picName;
	}
	
	public String getImagePath() {
		if(picName!=null && !StringUtil.isEmpty(picName.getAttachmentId())) {
			imagePath = "/attach/showPicture?attachmentId="+picName.getAttachmentId()+"&isThumbnail=true";
		}else {
			imagePath="暂无图片";
		}
		return imagePath;
	}

图片路径实体类

public class Attach implements Serializable{

    private static final long serialVersionUID = 1L;
    private String attachmentId;
    private String attachmentName; 
    private String entityId;
}

业务列表数据查询,查询返回的封装数据。直接把当前表的主键传入图片路径表

 
 

	 

图片路径表的接口获取业务表的Id,根据id获取图片存放的路径

public interface AttachParMapper {
	
	public Attach findById(String COMMENT_GOOD_ID);
}


	

三、layui增加页签

增加页签

	 layui.use('element', function(){
		  var element = layui.element;
		 var retData= $.getData(CONTEXT_PATH+"/Statu");
		 if(retData.status ==SUCCESS){
			 if(retData.data){
				 var url=CONTEXT_PATH+"/show/showList";
				  element.tabAdd('applyTab', {
					   title: '思想汇报'
					  ,content: $.loadHtml(url) //支持传入html
					  ,id: 'thougthReport'
					});
			 }
		 }
		});

监听页签

  • 已报名
  • 未报名
layui.use('element', function(){ var element = layui.element; element.init(); element.on('tab(attend)', function(data){ var index = data.index; if(index==1){ var url = CONTEXT_PATH + '/my/list'; var showMyList = new ShowMyList("activityList", "activityId", url); showMyList.render(); } }); });

关于layui页签变换监听相应页签下的列表界面的按钮

  
  • 奖励信息
  • 处罚信息
layui.use('element', function(){ var element = layui.element; element.init(); element.on('tab(goodorbad)', function(data){ var index = data.index; if(index==1){ var url = CONTEXT_PATH + '/Pub/list'; var showPubList = new ShowPubList("PublishList", "PubId", url); showPubList.render(function(_self,layui){ $('button[action="edit(this,event);"]').unbind('click').bind('click', function(){ var action = "_self.edit(this,event);"; eval(action); }); $('button[action="add(this,event);"]').unbind('click').bind('click', function(){ var action = "_self.add(this,event);"; eval(action); }); $('button[action="del(this,event);"]').unbind('click').bind('click', function(){ var action = "_self.del(this,event);"; eval(action); }); $('button[action="view(this,event);"]').unbind('click').bind('click', function(){ var action = "_self.view(this,event);"; eval(action); }); }); } if(index==0){ var url = CONTEXT_PATH + '/pub/list'; var showpubList = new ShowpubList("pubList", "pubId", url); showpubList.render(function(_self){ $('button[action="edit(this,event);"]').unbind('click').bind('click', function(){ var action = "_self.edit(this,event);"; eval(action); }); $('button[action="add(this,event);"]').unbind('click').bind('click', function(){ var action = "_self.add(this,event);"; eval(action); }); $('button[action="del(this,event);"]').unbind('click').bind('click', function(){ var action = "_self.del(this,event);"; eval(action); }); $('button[action="view(this,event);"]').unbind('click').bind('click', function(){ var action = "_self.view(this,event);"; eval(action); }); }); } });

四、layui 列表页换页不能保存前一页勾选的数据

layui监听复选框的值

//复选框事件选中以后回调
				layui.table.on('checkbox(' + _self.container + ')', function(obj){
					if(_self.tableAfterChecked && $.isFunction(_self.tableAfterChecked)){
						 _self.tableAfterChecked(obj); 					//回调 子类中的 钩子方法
					}
				});

前台html存选中的id

	@RequestMapping (value="/user/showUserList")
	public String showUserList(Model model,String ids){
		model.addAttribute("userIds", ids);
		return "select/user/showUserList";
	}


	

layui列表界面js

var initParam=$("input[name='userIds']").val().split(',')||[];
var ShowUserList = ListPager.extend({
	init : function(container, primaryKey, url){
		var _self = this;
			
	     ]]; 
		//插件是基于layui封装的, layOption是对layui的参数扩展(具体api参照layui属性)
		this.dataArr = new Array();
	},
	initLayuiPlugin: function(){
		this._super();
		
	},
	initEvent: function(){
		this._super();
		
		//TODO 父类仅仅绑定了工具条通用按钮事件, 如有其他事件请在这里定义
	},
	User : function(curDom, event){
		debugger;
		var _self = this;
		/*var data = _self.getSelectRows();*/
		var data = _self.dataArr;
		if(data.length == 0){
			return;
		}
	
	},afterDone:function(thi,cum){ //初始化进入界面的时候给全局数组initParam赋值
		
		var _self=this;
		var ids=$("#UserList").next(".layui-form").children(".layui-table-body").find("td[data-field='userCode']");
		for(var i=0;i

layui 查询选择与保存展示勾选

定义全局变量

//初始化传递参数

var initParam=$("input[name='members']").val().split(',')||[];
var initParamName = $("input[name='membersName']").val();
var paramName = initParamName.substring(0,initParamName.length-1);

//页面展示字典翻译封装参数
var codeName=new Array();
for(var i=0;i

查询选择框事件

,afterDone:function(thi,cum){ //页面加载显示勾选数据
		
		var _self=this;
		var ids=$("#mmberSelectList").next(".layui-form").children(".layui-table-body").find("td[data-field='userId']");
		for(var i=0;i

查询选择框保存事件

	querySelectCallbackData = function () {
		var idArr = [];
		for(i=0,len=codeName.length; i

layui JS框架

if(_self.afterDone && $.isFunction(_self.afterDone)){
				_self.afterDone(this,_self.container);
			}
	//复选框事件选中以后回调
				layui.table.on('checkbox(' + _self.container + ')', function(obj){
					if(_self.tableAfterChecked && $.isFunction(_self.tableAfterChecked)){
						 _self.tableAfterChecked(obj); 					//回调 子类中的 钩子方法
					}
				});

查询选择layui的js框架

querySelect : function(thi,event){
			var param=$("#" + this.settings.fieldCode + "-popSelector").find("input[type='hidden']").val();
			var _self = this;
			var url = "";
			var urlParam=_self.settings.url;
			if(urlParam.indexOf("?") != -1 ){
				url=CONTEXT_PATH + urlParam+"&ids="+param;
			}else{
				url = CONTEXT_PATH + urlParam+"?ids="+param;
			}
			var layIndex = layer.open({
	        	type: LayuiPopStyle.LAYUI_IFRAME_LAYER,
	        	title: "查询选择",
	        	maxmin: false,
				shadeClose: false, 				//开启遮罩关闭
	        	area: _self.settings.area,
	        	btn: ['确认', '取消'],
	        	content: url,
	        	success: function(layero){
	        	},
	        	yes: function(index, layero){	//如果设定了yes回调,需进行手工关闭
	        		//当点击‘确定’按钮的时候,获取弹出层返回的值
	        		var dataArr = window["layui-layer-iframe" + index].querySelectCallbackData();
	        		
	        		if(dataArr.length == 0){
	        			layer.msg("只能选择数据...", {icon: 5});
	        			return false;
	        		}
	        		
	        		if(!eval(_self.settings.multi) && dataArr.length > 1){  //默认单选
	        			layer.msg("只能选择一条数据...", {icon: 5});
	        			return false;
	        		}
	        		
	        		var _keys = _self.settings.code,
	        			code = "",
	        			name = "";
	        		    userId = "";
	        		if(!_self.settings.multi){
	        			code = dataArr[0]['code'];
	        			name = dataArr[0]['name'];
        			}else{
        				var _code = "",
        					_name = "";
        				    _userId="";
            			for(var i=0,len=dataArr.length; i1)
            			{
            			   userId += _userId.substring(0,_userId.length-1);
            			}
        			}
	        		
	        		//给input[name='']:text 赋值
	        		$("input[name='" + _keys[0] + "']:hidden").val(code);
	        		$("input[name='" + _keys[1] + "']:text").val(name);
	        		$("textarea[name='"+ _keys[1] + "']").val(name);
	        		if(!$.isEmptyStr(userId))
	        		{
	        			$("input[name='orgUserId']:hidden").val(userId);
	        		}
	    		    layer.close(index); 
	    		},
	        	end: function(){		//销毁列表回调方法
	        	},
	        	cancel: function(){ 	//点击左上角关闭按钮回调方法
	        	}
	        	
	        });
			
		}

五、layui提交表单数据

layui.form.on 

提交按钮

layui.form.on('submit(yesFLowNodeVO)', function(data){
			//处理 	KindEditor 富文本取值问题
		    debugger;
		    var formDoms = data["form"];
		    
			var url = CONTEXT_PATH +"/adviceAudit/save";
			
			var toMessage =data.field.toMessage;
		    
		    var auditReason=data.field.auditReason;
		    var adviceStatus = "2";
			var param ={
					"toMessage":$.toJSON(toMessage),"auditReason":$.toJSON(auditReason),"adviceStatus":$.toJSON(adviceStatus)
			}
			var retData = $.getData(url, param);
			if(retData.status!=1000 || retData.status == WebConst.FAIL){
				if(!$.isEmptyStr(retData.message))
				{
					layer.msg(retData.message, {icon: 5});
					return false;
				}
				layer.msg('保存失败', {icon: 5});
				return false;
			}
			
				layer.msg('保存成功', {icon: 6});

			return false;
		});

六、layui表单定义二级字典

html

			

js根据获取的数据动态生成select 的option

layui.form.on('select(reason)', function(data){
		  debugger;
		  var url = CONTEXT_PATH+"/dictionary/dictionaryItemList";
			var param = {
					"dictCode":data.value
			};
			$("#punishreasontwo option").remove();
			var data = $.getData(url,param);
			var punishreason = $("#punishreasontwo");
			if(data.length==0){
				$("#punishreasontwodiv").attr("style","display: none;");
				return;
			}else{
				$("#punishreasontwodiv").attr("style","display: ;");
			}
			punishreason.append("");
			$(data).each(function(index,obj){
				punishreason.append("");
			});
			
			layui.form.render('select');
		});
		
		var params = {
				"rewardpubId":$.QueryString("entityId")
		};
			var data = $.getData(CONTEXT_PATH + '/publish/get1',params);
			if(data && data.status == WebConst.SUCCESS && data.data){
				var reason = data.data.punishreasonone;
				var url = CONTEXT_PATH+"/dictionary/dictionaryItemList";
					var param = {
							"dictCode":reason
					};
					var data = $.getData(url,param);
					var punishreason = $("#punishreasontwo");
					$("#punishreasontwo option").remove();
					punishreason.append("");
					$(data).each(function(index,obj){
						punishreason.append("");
					});
					layui.form.render('select');
			}

后台返回实体类封装返回的数据

private String rewardName;
private String punishreasonone;
    private String punishreasontwo;
    
    public String getPunishreasonone() {
		return punishreasonone;
	}
	public void setPunishreasonone(String punishreasonone) {
		this.punishreasonone = punishreasonone;
	}
	public String getPunishreasontwo() {
		return punishreasontwo;
	}
	public void setPunishreasontwo(String punishreasontwo) {
		this.punishreasontwo = punishrea
    
    /**
     * 设置原因
     * @param rewardName
     */
    public void setRewardName(String rewardName) {
    	if(StringUtil.isNotEmpty(rewardName) && rewardName.split(",").length == 1) {
    		punishreasonone = rewardName.split(",")[0];
    	}
    	if(StringUtil.isNotEmpty(rewardName) && rewardName.split(",").length == 2) {
    		punishreasonone = rewardName.split(",")[0];
    		punishreasontwo = rewardName.split(",")[1];
    	}
    	this.rewardName = rewardName;
    }


	public String getRewardNames() {
		rewardNames="";
		if(StringUtil.isEmpty(punishreasontwo)) {
			String dictName=DictContext.getInstance().getDict("punishreason", punishreasonone);
			if(!StringUtil.isEmpty(dictName)) {
				rewardNames=dictName;
			}
		}
		if(StringUtil.isNotEmpty(punishreasontwo)) {
			String dictName=DictContext.getInstance().getDict(punishreasonone, punishreasontwo);
			if(!StringUtil.isEmpty(dictName)) {
				rewardNames=dictName;
			}
		}
		return rewardNames;
	}

七、layui模态窗口加载ztree树形菜单

引入的ztree








ztree获取树形菜单

html




	<#include "/common/header.html"/>
	


    layui初始化ztree

    js

    var showOrgTree = {
    	init: function(){
    		var _self = this;
    		//利用layui 绘制表单元素
    		layui.use(['element', 'form', 'laydate', 'layer'], function(){
    			layui.form.render();
    		});
    		_self.initTree();
    		_self.initEvent();
    	},
    	initTree(){
    		var _self = this;
    	    var setting = {
    	            view: {},
    	            check: {
    	                enable: true
    	            },
    	            data: {
    	            	key: {
    	        			name: "orgName",
    	        			open: "isOpen"
    	        		},
    	                simpleData: {
    	                    enable: true,
    	        			idKey: "pbPartyOrgId",
    	        			pIdKey: "lastOrg",
    	        			rootPId: null
    	                }
    	            },
    	            check: {
    	        		enable: true,
    	        		chkboxType: { "Y": "", "N": "" }
    	        	},
    	            callback: {
    	            	beforeClick: _self.zTreeOnClick
    	        	}
    	        };
    	    var userFlag = $("#userFlag").val();
    	    var zNodes = $.getData(CONTEXT_PATH + "/pbPartyOrg/queryPartyOrgList?userFlag="+userFlag,null);
    	    var ztree = $.fn.zTree.init($("#orgDeptTree"), setting, zNodes);
    	    var treeObj = $.fn.zTree.getZTreeObj("orgDeptTree");
    	      treeObj.expandAll(true);
    	    var ids = $.QueryString("ids");
    	    if(!ids == ""){
    	    	var orgIds = ids.split(",");
    		    for(var i = 0 ; i

    layui模态窗口加载ztree的html

    模态窗口的html

       当前组织机构:
    	   
       
       
       选择组织
      

    js

    $(function(){
    	initData();
    });
    
    function initData(){
      sex();
      nation();
      age();
    }
    
    function openOrgTree(){
    	 var url = CONTEXT_PATH+"/pbPartyOrg/choicePartyOrg";
    	/* layer.open({
    		type: 2,
          title: '选择组织机构',
          area: ['68%', '66%'],
          maxmin: true,
          shadeClose: false, //开启遮罩关闭
          content:url,
          success : function(layero){
          },
          cancel: function(){
            }
    	});*/
    	 layer.open({
         	type: 2,
         	title: "选择组织机构",
         	maxmin: false,
    		shadeClose: false, 				//开启遮罩关闭
         	area: ['68%', '66%'],
         	btn: ['确认', '取消'],
         	content: url,
         	success: function(layero){
         	},
         	yes: function(index, layero){	//如果设定了yes回调,需进行手工关闭
         		//当点击‘确定’按钮的时候,获取弹出层返回的值
         		var dataArr = window["layui-layer-iframe" + index].querySelectCallbackData();
         		
         		if(dataArr.length == 0){
         			layer.msg("请选择一个组织机构...", {icon: 5});
         			return false;
         		}
         		
         		if(dataArr.length > 1){  //默认单选
         			layer.msg("只能选择一个组织机构...", {icon: 5});
         			return false;
         		}
    
    			var _code = "",
    				_name = "";
    			for(var i=0,len=dataArr.length; i

    八、layui上传图片

    html

    				

    js

    var ShowUser= CardPager.extend({
    	init: function(filter, url){
    		debugger;
    		this._super(filter, url);
    		//界面需要引用的插件
    		this.plugins = ['element', 'form', 'layedit', 'upload', 'laydate', 'layer'];
    		this.primaryKey = "userId";
    		this.primaryValue = $.QueryString("entityId");
    		this.dataUrl = CONTEXT_PATH + '/user/get';
    		this.entityName = "user";
    		var imagePath = $("#imagePath").val();
    		$("#userPhone").attr('src',imagePath);
    	},
    	initLayuiPlugin: function(){
    		this._super(); 
    		var _self = this;
    		_self.files = null;
    		layui.laydate.render({
    			elem: '#birthDate'
    		});
    		//执行实例
    		$.renderUpload({
    			fieldName : "照片",							//业务字段名称
    	    	fieldCode : "dealPicture",							//业务字段编码
    	    	entityName : "user",									//业务实体
    	    	selfFiles : _self.files
    		});
    	},
    	initEvent: function(){
    		this._super();
    		var _self = this;
    		_self.uploadUserPic();
    		//TODO 父类只定义了 保存事件,其他事件在这里进行定义
    	},
    	initThirdPlugin: function(){
    		var _self = this;
    	},
    	uploadUserPic:function(){
    		
    		 var uploadDoc = layui.upload.render({
    	            elem:'#test1',
    	            accept: 'images',
    	            url:CONTEXT_PATH+"/attach/upload",
    	            data:{																	//上传参数
    			    	"entityName" : "personalUser",							
    			    	"fieldCode" : "userId",								
    			    	"fieldName" : "userId",								
    			    },	
    	            before:function(obj){
    	                obj.preview(function(index, file, result){
    	                    $('#userPhone').attr('src', result);
    	                });
    	            },
    	            done:function(res, index, upload){
    	                if(res && res.status == WebConst.SUCCESS){//自定义返回失败
    	                	//$($("iframe[src='/partyMember/detail?act=add']").contents().find("#partyMemberForm")).setValues(ptParam);
    //	                	$("#docDemo").attr("src",CONTEXT_PATH+"/attach/showPicture?attachmentId="+res.data['attachmentId']+"&isThumbnail=true&date="+new Date().getTime());
    	                	$("#uploadAttachmentIds").val(res.data['attachmentId']);
    	                	/*return layer.msg('请点击提交个人资料上传图片');*/
    	                }else{
    	                   /* layer.msg('请点击提交个人资料上传图片');*/
    	                }
    	            },
    	            error:function(){
    	               var demoText = $('#demoText');
    	                demoText.html('上传失败 重试');
    	                demoText.find('.demo-reload').on('click', function(){
    	                    uploadDoc.upload();
    	                });
    	            }
    	        });
    	}
    });
    
    $(function(){
    	showUser = new ShowUser('user', CONTEXT_PATH + '/user/save');
    	showUser.render(function(data,_self){
    		debugger;
    		var imagePath = CONTEXT_PATH+$("#imagePath").val();
    		$("#userPhone").attr('src',imagePath);
    		
    		//如果有附件,上传附件
    		layui.form.on('submit(' + _self.filter + ')', function(data){
    			//处理 	KindEditor 富文本取值问题
    			var formDoms = data["form"];
    			for(i=0,len=formDoms.length; i0){
    			var url = CONTEXT_PATH + '/attach/delete/datafile';
    			$.getData(url,{'attachmentIds':unuploadFiles.join(",")});
    		}
    	}
    	
    });
    
    
    

    后台

    User实体类

    	private Attach picName;
    	private String imagePath = null;
    	public Attach getPicName() {
    		return picName;
    	}
    	public void setPicName(Attach picName) {
    		this.picName = picName;
    	}
    	
    	public String getImagePath() {
    		if(picName!=null && !StringUtil.isEmpty(picName.getAttachmentId())) {
    			imagePath = "/attach/showPicture?attachmentId="+picName.getAttachmentId()+"&isThumbnail=true";
    		}else {
    			imagePath="暂无图片";
    		}
    		return imagePath;
    	}
    	public void setImagePath(String imagePath) {
    		this.imagePath = imagePath;
    	}
    

    附件实体类

    public class Attach implements Serializable{
    
    	private static final long serialVersionUID = 1L;
    	private String attachmentId;
        private String attachmentName; 
        private String entityId;
        private String entityName;
        private String fieldName;
    	public String getAttachmentName() {
    		return attachmentName;
    	}
    	public void setAttachmentName(String attachmentName) {
    		this.attachmentName = attachmentName;
    	}
    	
    	public String getEntityId() {
    		return entityId;
    	}
    	public void setEntityId(String entityId) {
    		this.entityId = entityId;
    	}
    	public String getAttachmentId() {
    		return attachmentId;
    	}
    	public void setAttachmentId(String attachmentId) {
    		this.attachmentId = attachmentId;
    	}
    	public String getEntityName() {
    		return entityName;
    	}
    	public void setEntityName(String entityName) {
    		this.entityName = entityName;
    	}
    	public String getFieldName() {
    		return fieldName;
    	}
    	public void setFieldName(String fieldName) {
    		this.fieldName = fieldName;
    	}
        
    }

    查询接口

      	
    	    
              
      	
    
     	
    	    
    	    
    	    
    	    
    	     
      	
      	
      	

    上传附件js框架

    (function(scope){
    	var CardPager = Class.extend({
    		init: function(filter, url){
    			this.filter = filter;
    			this.url = url;
    		},
    		render: function(afterRender){
    			var _self = this;
    			_self.initThirdPlugin(); 		//初始化第三放插件
    			
    			//plugins 这个可以不传,但是请不要传空数组过来
    			var plugins = _self.plugins || ['form'];
    			layui.use(plugins,function(){
    				debugger;
    				_self.initEvent();
    				_self.initLayuiPlugin();	//初始化layui组件		
    				//渲染表单数据
    				debugger;
    				var params = {};
    					params[_self.primaryKey] = _self.primaryValue;
    				$.ajaxReq(_self.dataUrl, params, function(data){
    					if(data && data.status == WebConst.SUCCESS && data.data){
    						debugger;
    						var cardForm = $("#"+_self.filter+"Form"),
    							formDoms = cardForm[0];
    						cardForm.setValues(data.data);
    						//处理富文本赋值问题
    						for(i=0,len=formDoms.length; i';
    									 attachImg = '';
    								 }
    								 else if(!$.isEmptyStr(cFile.fileName) && cFile.fileName.indexOf('pdf')!=-1)
    								 {
    									 attachImg = '';
    								 }
    								 else
    								 {
    									 attachImg = '';
    								 }
    								 var $tr = $([''
    							          , attachImg
    							          ,''+ cFile.fileName +''
    							          ,''+ cFile.fileSize +' kb'
    							          ,''+ cFile.createDate +''
    							          ,''
    							            ,'下载  '
    							            ,''
    							          ,''
    							        ,''].join(''));
    								  $tr.find('button').on('click',function(){
    									  var rlt = $.getData(CONTEXT_PATH + "/attach/delete/updflag",{'attachmentId':$(this).closest("tr").attr('attatchmentId')});
    									  if(rlt && rlt.status == '1000'){
    										  $(this).closest("tr").remove();
    									  }
    									  return false;
    								  });
    								 $("#" + tableBody).append($tr);
    							}
    						}
    					})
    				}
    			},WebConst.AJAX_FORM,null,false);
    		},
    		initThirdPlugin: function(){
    			
    		},
    		initLayuiPlugin: function(){
    			var _self = this;
    		},
    		initEvent: function(){
    			var _self = this;
    			layui.form.on('submit(' + _self.filter + ')', function(data){
    				//处理 	KindEditor 富文本取值问题
    				var formDoms = data["form"];
    				for(i=0,len=formDoms.length; i

    layui上传附件通用js

    /**
     * 上传附件通用JS (基于layerUI)
     */
    ;(function($){
    	
    	var defaults = {
    			url : "/attach/upload",		
    	    	fieldCode : "aboutDocument",						//业务字段编码
    	    	fieldName : "相关文件",								//业务字段名称
    	    	entityName : "template",							//业务实体
    	};
    	
    	
    	function renderUpload(options){
    		
    		this.settings = $.extend({},defaults,options);
    		this.settings.elem = "#" + this.settings.fieldCode;
    		this.settings.bindAction = "#" + this.settings.fieldCode + "_Action";				//上传操作按钮	
    		this.settings.layuiUploadPreview = "#"+ this.settings.fieldCode +"_preview";
    		this.settings.previewTableBody = "#"+ this.settings.fieldCode +"_Preview_Table";	//上传预览表格
    		this.init();
    	}
    	//为函数添加原型链上的方法
    	renderUpload.prototype = {
    		init: function(){
    			
    			    var that = this;
    				var uploadInst = layui.upload.render({
    					    elem: that.settings.elem											//绑定元素
    					    ,url: CONTEXT_PATH + that.settings.url 									//上传接口
    					    ,accept:'file'
    					    ,data:{																	//上传参数
    					    	"entityName" : that.settings.entityName,							//业务实体
    					    	"fieldCode" : that.settings.fieldCode,								//业务字段编码
    					    	"fieldName" : that.settings.fieldName,								//业务字段名称
    					    }								
    					  	,auto:false												//是否选完文件后自动上传	如果设定 false,那么需要设置 bindAction 参数来指向一个其它按钮提交上传
    					  	,size:0													//设置文件最大可允许上传的大小,单位 KB。不支持ie8/9;	0(即不限制)
    					  	,multiple:true
    					  	//是否允许多文件上传。设置 true即可开启。不支持ie8/9
    					  	,bindAction: that.settings.bindAction					//指向一个按钮触发上传,一般配合 auto: false 来使用。值为选择器或DOM对象,如:bindAction: '#btn'
    					    ,choose: function(res){									//选择文件后的回调函数
    					    	var layIndex = layer.open({
    					        	type: 1,
    					        	title: "预览",
    					        	maxmin: false,
    					        	area : ['40%', '40%'],
    					        	content:$(that.settings.layuiUploadPreview).removeAttr('style'),			//$.loadHtml(preUrl),
    					        	success: function(layero){
    					        		var demoListView = $(that.settings.previewTableBody).empty();
    					        		var files = that.settings.selfFiles = res.pushFile(); //将每次选择的文件追加到文件队列
    					        	      //读取本地文件
    					        		res.preview(function(index, file, result){
    					        	        var tr = $([''
    					        	          ,''+ file.name +''
    					        	          ,''+ (file.size/1024).toFixed(1) +' kb'
    					        	          ,'等待上传'
    					        	          ,''
    					        	            ,''
    					        	            ,''
    					        	          ,''
    					        	        ,''].join(''));
    					        	        
    					        	        //单个重传
    					        	        tr.find('.demo-reload').on('click', function(){
    					        	        	res.upload(index, file);
    					        	        });
    					        	        
    					        	        //删除
    					        	        tr.find('.demo-delete').on('click', function(){
    					        	        	
    						        	        delete files[index]; //删除对应的文件
    						        	        tr.remove();
    						        	        uploadInst.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
    						        	        if(Object.getOwnPropertyNames(files).length == 0){			//当上传预览没有文件时,关闭弹出框
    						        	        	 layer.close(layIndex);
    						        	        }
    					        	        });
    					        	        demoListView.append(tr);
    					        	      });
    					        	},
    					        	end : function(){	//layer销毁回调
    					        		$(that.settings.layuiUploadPreview).attr('style','display:none;');
    					        		$(that.settings.previewTableBody).empty();
    					        	},
    					        	cancel: function(){ 		  //右上角关闭回调
    					        	}
    					        });
    					    	
    					    }
    					  	,before: function(res){					//文件提交上传前的回调
    					  		$("tr",$(that.settings.previewTableBody)).find("td[name='upload-status']").text("上传中...");
    					  	}
    					    ,done: function(res, index, upload){					//执行上传请求后的回调。返回三个参数,分别为:res(服务端响应信息)、index(当前文件的索引)、upload(重新上传的方法,一般在文件上传失败后使用)
    					    	//上传完毕回调		"dealPicture_list_table"
    					    	if(res && res.status == WebConst.SUCCESS){
    					    		$(that.settings.bindAction).text("").text("上传成功");
    					    		delete that.settings.selfFiles[index];
    					    		//改变预览状态,将上传附件id存在	隐藏域中
    					    		$("tr[id='upload-"+ index +"']",$(that.settings.previewTableBody)).find("td[name='upload-status']").text("附件缓存完毕,请点击提交上传附件");
    					    		var unupload = $("#uploadAttachmentIds").data("uploadAttachmentIds");
    					    		if(unupload){
    					    			unupload.push(res.data['attachmentId']);
    					    			$("#uploadAttachmentIds").data("uploadAttachmentIds",unupload);
    					    		}else{
    					    			if(res.data){
    					    				$("#uploadAttachmentIds").data("uploadAttachmentIds",[res.data['attachmentId']]);
    					    				/**
    					    				 * 第一个方法赋不了值,通过下面的赋值
    					    				 */
    					    				$("#uploadAttachmentIds").val([res.data['attachmentId']]);
    					    			}
    					    		}
    					    		
    					    		//处理卡片页面列表展示问题
    					    		var afile = res.data;
    					    		var attachImg = "";
    					    		if(!$.isEmptyStr(afile.fileName) && (afile.fileName.indexOf('docx')!=-1 
    										 || afile.fileName.indexOf('doc')!=-1))
    								 {
    									 //attachImg = '';
    									 attachImg = '';
    								 }
    								 else if(!$.isEmptyStr(afile.fileName) && afile.fileName.indexOf('pdf')!=-1)
    								 {
    									 attachImg = '';
    								 }
    								 else
    								 {
    									 attachImg = '';
    								 }
    					    		var $tr = $([''
    							          , attachImg
    							          ,''+ afile.fileName +''
    							          ,''+ afile.fileSize +' kb'
    							          ,''+ afile.createDate +''
    							          ,''
    							            ,'下载  '
    							            ,''
    							          ,''
    							        ,''].join(''));
    								  	$tr.find('button').on('click',function(){
    								  		var attId = $(this).closest("tr").attr('attatchmentId');
    								  		var url = CONTEXT_PATH + '/attach/delete/datafile';
    								  		var rlt = $.getData(url,{'attachmentIds':attId});
    										if(rlt && rlt.status == WebConst.SUCCESS){
    											  $(this).closest("tr").remove();
    											  $("#uploadAttachmentIds").data("uploadAttachmentIds").removeByValue(attId);
    										  }
    										return false;
    								  	});
    								  $("#" + afile.fieldCode + "_list_table").append($tr);
    					    	}
    					    }
    				    ,error: function(index, upload){						//执行上传请求出现异常的回调(一般为网络异常、URL 404等)。返回两个参数,分别为:index(当前文件的索引)、upload(重新上传的方法)
    				      //请求异常回调
    				    }
    				});
    			}
    	}
    	
    	//扩展jquery类方法
    	$.extend({
    		renderUpload : function(options){
    			return new renderUpload(options);
    		}
    	});
    })(jQuery);
    
    
    

    jsp嵌入layui上传附件组件

     
    
    
    
    "/>
    
         
                  
    缩略图 文件名 文件路径 上传时间 操作

    js

    var root = null;
    var ids = null;
    
    $(document).ready(function() {
    	root = $("#root").val();
    	ids = $("#ids").val();
    	initpage();
    });
    
    function initpage(){
    	root = $("#root").val();
    
    	if(null!=ids&&ids.length>0){
    		readAfv();
    		readFile(ids);
    	}
    	var timer = "";
    	$("#save").click(function(){
    		/*保存之前,要先把数据库中FILEATTACHMENT查出来,然后一并保存*/
    		var fileAtIds = "";
    		if(null!=ids&&ids.length>0){
    			param = {"ids":ids}
    		    $.ajax({  
    		        url:root + "/beforeSavePic",  
    		        data:param,  
    		        type:"post",  
    		        dataType:"json",
    		        async: false,
    		        success:function(data){ 
    		        	debugger;
    		        	fileAtIds = data;
    		        	$("input[name='fileAtIds']").val(fileAtIds);
    		            
    		        },  
    		        error:function(){  
    		        	alert("服务器正忙,请稍后重试");  
    		        }  
    		    }) 
    		}else{
    			var afvFId = $("input[name='afvFileId']").val();
    			if(null!=afvFId&&afvFId.length>0){
    				param = {"ids":afvFId}
    				  $.ajax({  
    				        url:root + "/beforeSavePic",  
    				        data:param,  
    				        type:"post",  
    				        dataType:"json",
    				        async: false,
    				        success:function(data){ 
    				        	fileAtIds = data;
    				        	$("input[name='fileAtIds']").val(fileAtIds);
    				            
    				        },  
    				        error:function(){  
    				        	alert("服务器正忙,请稍后重试");  
    				        }  
    				}) 
    			}
    
    		}
    		afvSave(fileAtIds);
    		$(this).attr("disabled", true); 
    		timer = setTimeout(function(){
    			debugger;
    			$("#save").attr("disabled", false); 
    		},20000);
    	})
    	
    }
    
    function afvSave(fileAtIds){
    	var fileAtIds=$("input[name='fileAtIds']").val();
    	param = {"fileAtIds":fileAtIds}
        $.ajax({  
            url:root + "/AddAfv",  
            data:param,  
            type:"post",  
            dataType:"json",  
            success:function(data){ 
            	/*保存之后,要把主键的值拿回来*/
            	$("input[name='afvFileId']").val(data);
            	$("input[id='ids']").val(data);
                alert("保存成功");  
            },  
            error:function(){  
            	alert("服务器正忙,请稍后重试");  
            }  
        }) 
    
      }
    
    
    function readAfv(){
    	var param = {"ids" : ids};
    	var uxl = root + "/queryAfv";
    	$.ajax({
         type : "POST",
         url : uxl,
         data : param,
         success : function(list) {
         	$.each(list,function(index,obj){
         		var afvFileId = obj.data.RECORD_VOLTAGE_ID;
         		$("input[name='afvFileId']").val(afvFileId);
         	});
         },
         error : function(data) {
              
         },
     });
    	return true;	
    }
    

    后台

    @Controller
    public class AddVoltageAfv {
    	@SuppressWarnings("unchecked")
    	@RequestMapping("/AddAfv")
    	@ResponseBody
    	public String Addxctyz(HttpServletRequest request, HttpServletResponse response) {
    		String fileAtIds = request.getParameter("fileAtIds");
    		JSONObject jsonObject = JSON.parseObject(requestParam);
    
    		String addIds = "";
    		if (null != ids && ids.length() > 0) {
    			String delSql1 = "delete from RECODR_MAINTAIN_VOLTAGE where RECORD_VOLTAGE_ID=?";
    			Object paramd1 = ids;
    			SqlUtil.getExecutor().execute(delSql1.toString(), paramd1);
    			
    			 String sqlSearch ="select decode(max(RECORD_VOLTAGE_ID),null,0,max(RECORD_VOLTAGE_ID)+1) RECORD_VOLTAGE_ID from RECODR_MAINTAIN_VOLTAGE";
    			 IBean queryOne = SqlUtil.getExecutor().queryOne(sqlSearch);
    			  addIds = queryOne.get("RECORD_VOLTAGE_ID", "");
    			
    			Object[] params = { addIds,orandid, volType,fileAtIds};
    			String sql = "insert into RECODR_MAINTAIN_VOLTAGE(RECORD_VOLTAGE_ID,RECORD_VOLTAGE_DATE,DEVICEASSOC_ID,VOLTAGE_TYPE,FILEATTACHMENT) VALUES(?,(select to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') from dual),?,?,?)";
    			SqlUtil.getExecutor().execute(sql.toString(), params);
    
    		} else {
    			 String sqlSearch ="select decode(max(RECORD_VOLTAGE_ID),null,0,max(RECORD_VOLTAGE_ID)+1) RECORD_VOLTAGE_ID from RECODR_MAINTAIN_VOLTAGE";
    			 IBean queryOne = SqlUtil.getExecutor().queryOne(sqlSearch);
    			  addIds = queryOne.get("RECORD_VOLTAGE_ID", "");
    			
    			Object[] params = { addIds,orandid, volType,fileAtIds};
    			String sql = "insert into RECODR_MAINTAIN_VOLTAGE(RECORD_VOLTAGE_ID,RECORD_VOLTAGE_DATE,DEVICEASSOC_ID,VOLTAGE_TYPE,FILEATTACHMENT) VALUES(?,(select to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') from dual),?,?,?)";
    			SqlUtil.getExecutor().execute(sql.toString(), params);
    
    		}
    		return addIds;
    	}
    
    @RequestMapping("/getFileAttachment")
    	@ResponseBody
    	public List getFileAttachment(HttpServletRequest request, HttpServletResponse response) {
    		 String str = request.getParameter("id");
    		 String sql ="select t.fileattachment from recodr_maintain_voltage t where t.record_voltage_id ="+str;
    		 IBean queryOne = SqlUtil.getExecutor().queryOne(sql);
    		 String attachmentIds = queryOne.get("FILEATTACHMENT", "");
    		 String[] strs = attachmentIds.split(",");
    		 List retList = new ArrayList();
    		 for(String id:strs){
    			 String sqlids = "select a.* from BDC_ATTACHMENT a where a.attachmentid ="+id;
    			 IBean queryAttach = SqlUtil.getExecutor().queryOne(sqlids);
    			 retList.add(queryAttach);
    		 }
    		 return retList;
    	}
    	
    	
    	@RequestMapping("/beforeSavePic")
    	@ResponseBody
    	public String beforeSavePic(HttpServletRequest request, HttpServletResponse response) {
    		 String str = request.getParameter("ids");
    		 String sql ="select t.fileattachment from recodr_maintain_voltage t where t.record_voltage_id ="+str;
    		 IBean queryOne = SqlUtil.getExecutor().queryOne(sql);
    		 String attachmentIds = queryOne.get("FILEATTACHMENT", "");
    		 return attachmentIds;
    	}
    	
    	
    	@RequestMapping("/removeFileAttachment")
    	@ResponseBody
    	public Boolean removeFileAttachment(HttpServletRequest request){
    		String mainId = request.getParameter("mainId");
    		String attId = request.getParameter("attId");
    		String sql = "update RECODR_MAINTAIN_VOLTAGE set FILEATTACHMENT = ? where RECORD_VOLTAGE_ID =?";
    		Object[] params ={attId,mainId};
    		 boolean ztlist= SqlUtil.getExecutor().execute(sql, params);
    		 if(ztlist){
    			 return true;
    		 }else{
    			 return false;
    		 }
    	}
    

    layui上传附件控制上传附件大小

    	layui.use('upload', function(){
    			  var upload = layui.upload;
    			  var that = new Object();
    			  that.settings = {};
    			  that.settings.bindAction="#dealPicture_Action";
    			  that.settings.elem="#dealPicture";
    			  that.settings.entityName="advice";
    			  that.settings.fieldCode="dealPicture";
                  that.settings.fieldName="上传附件";
                  that.settings.layuiUploadPreview="#dealPicture_preview";
                  that.settings.previewTableBody = "#dealPicture_Preview_Table";
                  that.settings.selfFiles = null;
                  that.settings.url="/attach/upload";
    			  //执行实例
    			  var uploadInst = upload.render({
    				    elem: that.settings.elem											//绑定元素
    				    ,url: CONTEXT_PATH + that.settings.url 									//上传接口
    				    ,accept:'file'
    				    ,data:{																	//上传参数
    				    	"entityName" : that.settings.entityName,							//业务实体
    				    	"fieldCode" : that.settings.fieldCode,								//业务字段编码
    				    	"fieldName" : that.settings.fieldName,								//业务字段名称
    				    }								
    				  	,auto:false												//是否选完文件后自动上传	如果设定 false,那么需要设置 bindAction 参数来指向一个其它按钮提交上传
    				  	,size:0													//设置文件最大可允许上传的大小,单位 KB。不支持ie8/9;	0(即不限制)
    				  	,multiple:true
    				  	//是否允许多文件上传。设置 true即可开启。不支持ie8/9
    				  	,bindAction: that.settings.bindAction					//指向一个按钮触发上传,一般配合 auto: false 来使用。值为选择器或DOM对象,如:bindAction: '#btn'
    				    ,choose: function(res){									//选择文件后的回调函数
    				    	debugger;
    				    	var layIndex = layer.open({
    				        	type: 1,
    				        	title: "预览",
    				        	maxmin: false,
    				        	area : ['40%', '40%'],
    				        	content:$(that.settings.layuiUploadPreview).removeAttr('style'),			//$.loadHtml(preUrl),
    				        	success: function(layero){
    				        		var demoListView = $(that.settings.previewTableBody).empty();
    				        		var files = that.settings.selfFiles = res.pushFile(); //将每次选择的文件追加到文件队列
    				        	      //读取本地文件
    				        		res.preview(function(index, file, result){
    				        			if((file.size/1024)>1024){
    				        				layer.msg('上传的附件不能超过1M', {icon: 5});
    				        				that.settings.selfFiles=null;
    				        				delete files[index];
    				        				layer.close(layIndex);
    				        				return false;
    				        			}
    				        	        var tr = $([''
    				        	          ,''+ file.name +''
    				        	          ,''+ (file.size/1024).toFixed(1) +' kb'
    				        	          ,'等待上传'
    				        	          ,''
    				        	            ,''
    				        	            ,''
    				        	          ,''
    				        	        ,''].join(''));
    				        	        
    				        	        //单个重传
    				        	        tr.find('.demo-reload').on('click', function(){
    				        	        	res.upload(index, file);
    				        	        });
    				        	        
    				        	        //删除
    				        	        tr.find('.demo-delete').on('click', function(){
    				        	        	
    					        	        delete files[index]; //删除对应的文件
    					        	        tr.remove();
    					        	        uploadInst.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
    					        	        if(Object.getOwnPropertyNames(files).length == 0){			//当上传预览没有文件时,关闭弹出框
    					        	        	 layer.close(layIndex);
    					        	        }
    				        	        });
    				        	        demoListView.append(tr);
    				        	      });
    				        	},
    				        	end : function(){	//layer销毁回调
    				        		$(that.settings.layuiUploadPreview).attr('style','display:none;');
    				        		$(that.settings.previewTableBody).empty();
    				        	},
    				        	cancel: function(){ 		  //右上角关闭回调
    				        	}
    				        });
    				    	
    				    }
    				  	,before: function(res){					//文件提交上传前的回调
    				  		$("tr",$(that.settings.previewTableBody)).find("td[name='upload-status']").text("上传中...");
    				  	}
    				    ,done: function(res, index, upload){					//执行上传请求后的回调。返回三个参数,分别为:res(服务端响应信息)、index(当前文件的索引)、upload(重新上传的方法,一般在文件上传失败后使用)
    				    	//上传完毕回调		"dealPicture_list_table"
    				    	if(res && res.status == WebConst.SUCCESS){
    				    		$(that.settings.bindAction).text("").text("上传成功");
    				    		delete that.settings.selfFiles[index];
    				    		//改变预览状态,将上传附件id存在	隐藏域中
    				    		$("tr[id='upload-"+ index +"']",$(that.settings.previewTableBody)).find("td[name='upload-status']").text("附件缓存完毕,请点击提交上传附件");
    				    		var unupload = $("#uploadAttachmentIds").data("uploadAttachmentIds");
    				    		if(unupload){
    				    			unupload.push(res.data['attachmentId']);
    				    			$("#uploadAttachmentIds").data("uploadAttachmentIds",unupload);
    				    		}else{
    				    			if(res.data){
    				    				$("#uploadAttachmentIds").data("uploadAttachmentIds",[res.data['attachmentId']]);
    				    				/**
    				    				 * 第一个方法赋不了值,通过下面的赋值
    				    				 */
    				    				$("#uploadAttachmentIds").val([res.data['attachmentId']]);
    				    			}
    				    		}
    				    		
    				    		//处理卡片页面列表展示问题
    				    		var afile = res.data;
    				    		var attachImg = "";
    				    		if(!$.isEmptyStr(afile.fileName) && (afile.fileName.indexOf('docx')!=-1 
    									 || afile.fileName.indexOf('doc')!=-1))
    							 {
    								 //attachImg = '';
    								 attachImg = '';
    							 }
    							 else if(!$.isEmptyStr(afile.fileName) && afile.fileName.indexOf('pdf')!=-1)
    							 {
    								 attachImg = '';
    							 }
    							 else
    							 {
    								 attachImg = '';
    							 }
    				    		var $tr = $([''
    						          , attachImg
    						          ,''+ afile.fileName +''
    						          ,''+ afile.fileSize +' kb'
    						          ,''+ afile.createDate +''
    						          ,''
    						            ,'下载  '
    						            ,''
    						          ,''
    						        ,''].join(''));
    							  	$tr.find('button').on('click',function(){
    							  		var attId = $(this).closest("tr").attr('attatchmentId');
    							  		var url = CONTEXT_PATH + '/attach/delete/datafile';
    							  		var rlt = $.getData(url,{'attachmentIds':attId});
    									if(rlt && rlt.status == WebConst.SUCCESS){
    										  $(this).closest("tr").remove();
    										  $("#uploadAttachmentIds").data("uploadAttachmentIds").removeByValue(attId);
    									  }
    									return false;
    							  	});
    							  $("#" + afile.fieldCode + "_list_table").append($tr);
    				    	}
    				    }
    			    ,error: function(index, upload){						//执行上传请求出现异常的回调(一般为网络异常、URL 404等)。返回两个参数,分别为:index(当前文件的索引)、upload(重新上传的方法)
    			      //请求异常回调
    			    }
    			  });
    			});

    layui提交保存

    		layui.form.on('submit(pre)', function(data){
    			//处理 	KindEditor 富文本取值问题
    			var formDoms = data["form"];
    			for(i=0,len=formDoms.length; i
    	//关闭卡片页面之前回调
    	function beforeClose (){
    		//如果涉及到文件上传,关闭卡片页面将未上传的附件进行删除
    		var unuploadFiles = $("#uploadAttachmentIds").data("uploadAttachmentIds");
    		if(unuploadFiles && unuploadFiles.length>0){
    			var url = CONTEXT_PATH + '/attach/delete/datafile';
    			$.getData(url,{'attachmentIds':unuploadFiles.join(",")});
    		}
    	}

    十、layui点击列表行操作

          
    ShowProduceList = ListPager.extend({
    	init : function(container, primaryKey, url){
    		//列表容器
    		this.container = container;
    		//主键字段
    		this.primaryKey = primaryKey;
    		//数据请求地址
    		this.url = url;
    		//界面需要引用的插件
    		this.plugins = ['table', 'element', 'form', 'laydate', 'layer','carousel'];
    //		//弹出卡片界面的大小[60%,80%]
    //		this.cardSize = ['100%','100%'];
    //		//弹出卡片界面方式:页面层(这里content是一个普通的String):1;iframe层(content是一个URl):2
    		this.cardPopStyle = 2;
    		//每页大小 
    		this.pageSize = 5;
    		//列表头
    		this.title = [[
    			{field: 'planCode', title: '计划单号', width: 120},
    			
    			{field: 'workCode', title: '工程编号', width: 120},
    			
    			{field: 'workName', title: '工程名称', width: 120},
    			
    			{field: 'address', title: '工程地址', width: 120},
    			
    			{field: 'workTime', title: '作业日期及时间', width: 120},
    			
    			{field: 'workOrg', title: '作业单位', width: 120},
    			
    			{field: 'coopOrg', title: '配合单位', width: 120},
    			
    			{field: 'preLevel', title: '压力级制', width: 120},
    			
    			{field: 'isDownPre', title: '是否降压', width: 120},
    			
    			{field: 'state', title: '状态', width: 100},
    			
    		/*	{fixed: 'right', title: '地图查看', align:'center',width: 80, toolbar: '#scanProduce'}*/
    	     ]]; 
    		//插件是基于layui封装的, layOption是对layui的参数扩展(具体api参照layui属性)
    		this.layOption = {
    				
    		};
    	},
    	initLayuiPlugin: function(){
    		debugger;
    		this._super();
    		layui.table.on('row(produceList)',function(obj){
    		 	var data = obj.data,
    		 	url = CONTEXT_PATH + '/cusviews/produce/listProduce';
    			var param = {
    					workId : data.workId,
    					page : 0,
    					limit : 10
    			}
    			var retData = $.getData(url,param);
    	/*		if(1000 != retData.status){
    				layer.msg('获取数据失败', {icon: 5});
    				return;
    			}*/
    			var points = [];
    			produce.removePoint();
    			produce.removeLine();
    			produce.closeInfoWindow();
    			var data = retData.data;
    			if(!$.isEmptyArray(data)){
    				for(var i=0;i");
    					content.push("
    "); content.push("

    工程名称:"+ data[i].workName +"

    "); content.push("

    计划单号:"+ data[i].planCode +"

    "); content.push("

    作业等级:"+ data[i].workLevel +"

    "); content.push("

    作业类别:"+ data[i].workType +"

    "); content.push("

    是否降压:"+ data[i].isDownPre +"

    "); content.push("

    作业状态:"+ data[i].state +"

    "); content.push("

    作业时间:"+ data[i].workTime +"

    "); content.push("

    作业单位:"+ data[i].workOrg +"

    "); content.push("

    坐标x:"+ data[i].lng +"

    "); content.push("

    坐标Y :"+data[i].lat +"

    "); drawPoint.type["infowindow"]={ content:content.join(""), xoffset: 0, yoffset:-31, width:360, height:100 }; drawPoint.type["onClick"]=function(point,e){ produce.showInfoWindow(point); } } } }) }, initEvent: function(){ this._super(); //TODO 父类仅仅绑定了工具条通用按钮事件, 如有其他事件请在这里定义 }, hookMethod:function(obj){ } }); $(function(){ var url = CONTEXT_PATH + '/cusviews/produce/listProduce'; var showProduceList = new ShowProduceList("produceList", "workId", url); showProduceList.render(); $(".tc_box .cbar").scrollBar(); })

    layui框架使用与代码编写_第3张图片

    十二、layui页面列表加载回调事件

    			//利用layui 绘制列表  ( url : _self.url+"?decAjaxReq=yes", 给ajax请求加密)
    			layui.use(plugins, function(){
    				debugger;
    				var option = $.extend({elem:  "#" + _self.container, 
    									   url : _self.url, 
    									   cols: _self.title,
    									   method: RequestMethod.METHOD_POST,
    									   id : _self.tableId,							
    									   even: true,
    									   page: true,									//是否显示分页
    									   pageNum: 1,
    									   limit: _self.pageSize, 						//每页默认显示的数量
    									   limits:[5,10,15,20,30],
    									   done:function(res, curr, count){
    										   debugger;
    										   if(_self.afterDone && $.isFunction(_self.afterDone)){
    						           				_self.afterDone(res, curr, count);
    						           			}
    									   }}, _self.layOption);
    				//展示已知数据
    				layui.table.render(option);
    				
    				//渲染部分layui组件
    				_self.initLayuiPlugin();
    				
    				//监听工具条
    				layui.table.on('tool(' + _self.container + ')', function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
    					if(_self.hookMethod && $.isFunction(_self.hookMethod)){
    						 _self.hookMethod(obj); 					//回调 子类中的 钩子方法
    					}
    				});
    				//复选框事件选中以后回调
    				layui.table.on('checkbox(' + _self.container + ')', function(obj){
    					if(_self.tableAfterChecked && $.isFunction(_self.tableAfterChecked)){
    						 _self.tableAfterChecked(obj); 					//回调 子类中的 钩子方法
    					}
    				});
    			});
    	initEvent: function(){
    		this._super();
    		//TODO 父类仅仅绑定了工具条通用按钮事件, 如有其他事件请在这里定义
    	},
    	afterDone:function(res, curr, count){
    		debugger;
    		Pile.drawPoint(res.data);
    	}

    layui框架使用与代码编写_第4张图片

    layui框架使用与代码编写_第5张图片

    十三、layOption的列表加载动态指定查询条件

          
          
          
          
    var Device = {
    	/**
    	 * 定位坐标
    	 */	
    	setCenter:function(lng,lat){
    		cntenMap.setCenter(lng,lat);
    	},
    	/**
    	 * 展示定位详情
    	 */
    	showInfoWindow:function(point){
    		cntenMap.showInfoWindow(point);
    	},
    	/**
    	 * 显示不同设备列表
    	 * type:station-调压站 box-调压箱 well-闸井 pile-阴极桩
    	 */
    	clickDeviceType:function(type){
    		if($.isEmptyStr(type)){
    			return;
    		}
    		var url = "";
    		switch(type)
    		{
    			case 'station':
    				url = CONTEXT_PATH + "/cusviews/dev/showStationList/1";
    				Device.removeDevicePoints(boxPoints);
    				Device.removeDevicePoints(wellPoints);
    				Device.removeDevicePoints(pilePoints);
    				break;
    			case 'box':
    				url = CONTEXT_PATH + "/cusviews/dev/showStationList/2";
    				Device.removeDevicePoints(stationPoints);
    				Device.removeDevicePoints(wellPoints);
    				Device.removeDevicePoints(pilePoints);
    				break;
    			case 'well':
    				url = CONTEXT_PATH + "/cusviews/dev/showWellList";
    				Device.removeDevicePoints(stationPoints);
    				Device.removeDevicePoints(boxPoints);
    				Device.removeDevicePoints(pilePoints);
    				break
    			case 'pile':
    				url = CONTEXT_PATH + "/cusviews/dev/showPileList";
    				Device.removeDevicePoints(stationPoints);
    				Device.removeDevicePoints(boxPoints);
    				Device.removeDevicePoints(wellPoints);
    				break;
    			default:
    				break;
    		}
    		$("#deviceListDiv").css("display","block");
    		$("#deviceListDiv").load(url)
    	},
    	@RequestMapping("/showStationList/{type}")
    	public String showStationList(@PathVariable("type")String type,ModelMap model)
    	{
    		model.addAttribute("stationType", type);
    		return "cusviews/v_devices/stationList";
    	}
          
    ShowStationList = ListPager.extend({
    	init : function(container, primaryKey, url){
    		//列表容器
    		this.container = container;
    		//主键字段
    		this.primaryKey = primaryKey;
    		//数据请求地址
    		this.url = url;
    		//界面需要引用的插件
    		this.plugins = ['table', 'element', 'form', 'laydate', 'layer'];
    //		//弹出卡片界面的大小[60%,80%]
    //		this.cardSize = ['100%','100%'];
    //		//弹出卡片界面方式:页面层(这里content是一个普通的String):1;iframe层(content是一个URl):2
    		this.cardPopStyle = 2;
    		//每页大小 
    		this.pageSize = 5;
    		//列表头
    		this.title = [[
    			{field: 'deviceName', title: '设备名称', width: 160},
    			
    			{field: 'deviceCode', title: '设备编号', width: 160},
    			
    			{field: 'startDate', title: '启用日期', width: 160},
    			
    			{field: 'deviceSpec', title: '设备规格', width: 160},
    			
    			{field: 'deviceModel', title: '设备型号', width: 160},
    			
    			{field: 'runState', title: '是否正常', width: 160},
    	     ]]; 
    		//插件是基于layui封装的, layOption是对layui的参数扩展(具体api参照layui属性)
    		this.layOption = {
    				where:{
    					preBoxType:$("#stationType").val()
    				}
    		};
    	},
    }
    $(function(){
    	var url = CONTEXT_PATH + '/cusviews/dev/listStation';
    	var showStationList = new ShowStationList("stationList", "deviceId", url);
    	showStationList.render();
    	Station.drawPoint();
    	$(".tc_box .cbar").scrollBar();
    })
    
    
    
    (function(scope){
    	
    	var ListPager = Class.extend({
    		init: function(){},
    		render: function(){
    			
    			var _self = this;
    			//弹出卡片界面的大小[60%,80%]
    			_self.cardSize = _self.cardSize || ['80%','80%'];
    			//弹出卡片界面方式:页面层(这里content是一个普通的String):1;iframe层(content是一个URl):2
    			_self.cardPopStyle = _self.cardPopStyle || LayuiPopStyle.LAYUI_IFRAME_LAYER;
    			_self.tableId = _self.container + "." + _self.primaryKey;
    			//plugins 这个可以不传,但是请不要传空数组过来
    			var plugins = _self.plugins || ['table','form'];
    			var p = _self.assemblyFormPrams();
    			//利用layui 绘制列表  ( url : _self.url+"?decAjaxReq=yes", 给ajax请求加密)
    			layui.use(plugins, function(){
    				var option = $.extend({elem:  "#" + _self.container, 
    									   url : _self.url, 
    									   cols: _self.title,
    									   method: RequestMethod.METHOD_POST,
    									   id : _self.tableId,							
    									   even: true,
    									   page: true,									//是否显示分页
    									   pageNum: 1,
    									   limit: _self.pageSize, 						//每页默认显示的数量
    									   limits:[5,10,15,20,30]}, _self.layOption);
    				//展示已知数据
    				layui.table.render(option);
    
    	scope.ListPager = ListPager;
    })(window);

    十四、layui templet 固定列

    {field: 'viewState', title: '查看', width: 100,templet:'#viewStateTpl'},
          

    layui列表框架

    (function(scope){
    	var ListPager = Class.extend({
    		init: function(){},
    		render: function(){
    			var _self = this;
    			//弹出卡片界面的大小[60%,80%]
    			_self.cardSize = _self.cardSize || ['80%','80%'];
    			//弹出卡片界面方式:页面层(这里content是一个普通的String):1;iframe层(content是一个URl):2
    			_self.cardPopStyle = _self.cardPopStyle || LayuiPopStyle.LAYUI_IFRAME_LAYER;
    			_self.tableId = _self.container + "." + _self.primaryKey;
    			//plugins 这个可以不传,但是请不要传空数组过来
    			var plugins = _self.plugins || ['table','form'];
    			var p = _self.assemblyFormPrams();
    			//利用layui 绘制列表  ( url : _self.url+"?decAjaxReq=yes", 给ajax请求加密)
    			layui.use(plugins, function(){
    				var option = $.extend({elem:  "#" + _self.container, 
    									   url : _self.url, 
    									   cols: _self.title,
    									   method: RequestMethod.METHOD_POST,
    									   id : _self.tableId,							
    									   even: true,
    									   page: true,									//是否显示分页
    									   pageNum: 1,
    									   limit: _self.pageSize, 						//每页默认显示的数量
    									   limits:[5,10,15,20,30]}, _self.layOption);
    				//展示已知数据
    				layui.table.render(option);
    				
    				//渲染部分layui组件
    				_self.initLayuiPlugin();
    				
    				//监听工具条
    				layui.table.on('tool(' + _self.container + ')', function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
    					if(_self.hookMethod && $.isFunction(_self.hookMethod)){
    						 _self.hookMethod(obj); 					//回调 子类中的 钩子方法
    					}
    				});
    				//复选框事件选中以后回调
    				layui.table.on('checkbox(' + _self.container + ')', function(obj){
    					if(_self.tableAfterChecked && $.isFunction(_self.tableAfterChecked)){
    						 _self.tableAfterChecked(obj); 					//回调 子类中的 钩子方法
    					}
    				});
    			});
    			//界面绘制完成, 初始化界面事件
    			_self.initEvent();
    		},
    		initLayuiPlugin: function(){
    			var _self = this;
    		},
    		initEvent: function(){
    			var _self = this;
    			//列表 增删改查
    			$("div[name='listBtns'] button").unbind('click').bind('click', function(){
    				var action = "_self." + $(this).attr("action");
    				eval(action);
    			});
    			
    			//列表查询、重置
    			$("div button[type='button']",$("#" + _self.container + "-QueryForm"))
    				.unbind('click')
    				.bind('click', function(){
    				var action = "_self." + $(this).attr("action");
    				eval(action);
    			});
    		},
    		assemblyFormPrams: function(){														//组装列表模糊查询表单数据
    			var _self = this;
    			var formParam = $("#" + _self.container + "-QueryForm").serializeArray(),
    			reqParam = {};
    			for(var o in formParam){
    				if(formParam[o]["name"]){
    					reqParam[formParam[o]["name"]] = formParam[o]["value"];
    				}
    			}
    			return reqParam;
    		},
    		listQuery: function(){
    			var _self = this;
    			layui.table.reload(_self.tableId, {
                    where: _self.assemblyFormPrams()
                });
    		},
    		/**
    		 * 获取选中的数据
    		 */
    		getSelectRows: function(){
    			var checkStatus = layui.table.checkStatus(this.tableId);
    			return checkStatus.data;
    		},
    		getSelectIds: function(){
    			var data = this.getSelectRows();
    			var ids = [];
    			if($.isEmptyArray(data))
    				return ids;
    			for(var i = 0; i < data.length; i++){
    				ids.push(data[i][this.primaryKey]);
    			}
    			return ids;
    		},
    		view: function(curDom, event){
    			var _self = this;
    			var data = _self.getSelectRows();
    			if (data.length != 1) {  
    				layer.msg("请选中一条数据进行查看");
    	            return;
    	        }
    			var url = $(curDom).attr("url") + "?act=" + WebConst.READ + "&entityId=" + data[0][_self.primaryKey];
    			var title = $(curDom).attr("title");
    			var layIndex = layer.open({
    			      type: this.cardPopStyle,
    			      title: title,
    			      maxmin: true,
    				  shadeClose: true, //开启遮罩关闭
    				  area : this.cardSize,
    			      content: this.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER ? $.loadHtml(url) : url,
    			      success: function(layero){
    			    	  	layero = _self.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER ? layero : layer.getChildFrame('body', layIndex);
    		        		if(_self.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER){
    		        			layero.setValues(data[0]);
    		        		}
    		        		layui.form.render();
    			      }
    			});
    		},
    		add: function(curDom, event){
    			var _self = this;
    			
    			//新增之前回调函数
    			if(_self.beforeAdd && $.isFunction(_self.beforeAdd)){
    				_self.beforeAdd();
    			}
    			
    			var url = $(curDom).attr("url") + "?act=" + WebConst.ADD;
    			var title = $(curDom).attr("title");
    			layer.open({
    				type: this.cardPopStyle,
    				title: title,
    				area: this.cardSize,
    				maxmin: true,
    				shadeClose: false, //开启遮罩关闭
    				content: this.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER ? $.loadHtml(url) : url,
    				success : function(layero){
    					layui.form.render();
    				},
    	        	end: function(){		//销毁列表回调方法
    	        		layui.table.reload(_self.tableId)
    	        		if(_self.closeCard && $.isFunction(_self.closeCard)){
    	        			return _self.closeCard();
    	    			}
    	        		return false;
    	        	},
    	        	cancel: function(){
    	        		
    	        	}
    			});
    		},
    		edit: function(curDom, event){
    			var _self = this;
    			var data = _self.getSelectRows();
    			if (data.length != 1) {  
    				layer.msg("请选中一条数据进行修改");
    	            return;
    	        }
    			
    			//修改之前回调函数
    			if(_self.beforeUpd && $.isFunction(_self.beforeUpd)){
    				_self.beforeUpd();
    			}
    			
    			var url = $(curDom).attr("url") + "?act=" + WebConst.EDIT + "&entityId=" + data[0][_self.primaryKey];
    			var title = $(curDom).attr("title");
    	        var layIndex = layer.open({
    	        	type: this.cardPopStyle,
    	        	title: title,
    	        	maxmin: true,
    				shadeClose: false, //开启遮罩关闭
    	        	area : this.cardSize,
    	        	content: this.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER ? $.loadHtml(url) : url,
    	        	success: function(layero){
    	        		layero = _self.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER ? layero : layer.getChildFrame('body', layIndex);
    	        		if(_self.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER){
    	        			layero.setValues(data[0]);
    	        			layui.form.render();
    	        		}
    	        	},
    	        	end: function(){		//销毁列表回调方法
    	        		layui.table.reload(_self.tableId)
    	        		if(_self.closeCard && $.isFunction(_self.closeCard)){
    	        			return _self.closeCard();
    	    			}
    	        		return false;
    	        	},
    	        	cancel: function(){ 	//点击左上角关闭按钮回调方法
    	        		if(_self.cardPopStyle == LayuiPopStyle.LAYUI_IFRAME_LAYER){  					//从列表调用卡片页面数据
    	        			var frameId = document.getElementById('layui-layer' + layIndex).getElementsByTagName("iframe")[0].id,
    	        			closeCallback = $('#'+frameId)[0].contentWindow.beforeClose;
    		        		if(closeCallback && $.isFunction(closeCallback)){
    		        			 return closeCallback();
    		        		}
    	        		}
    	        	}
    	        	
    	        });
    		},
    		del: function(curDom, event){
    			var _self = this;
    			var data = _self.getSelectIds();
    			if(data.length == 0){
    				layer.msg("请至少选择一条需要删除的数据");
    				return;
    			}
    			var url = $(curDom).attr("url") + "?act=" + WebConst.DELETE;
    			layer.confirm('确定删除吗', function(index){
    				layer.close(index);
    				$.ajaxReq(url,$.toJSON(data),function(){
    					layui.table.reload(_self.tableId)
    				});
    			});
    		}
    	});
    	scope.ListPager = ListPager;
    })(window);

    Class.js

    /* Simple JavaScript Inheritance
     * By John Resig http://ejohn.org/
     * MIT Licensed.
     */
    // Inspired by base2 and Prototype
    (function(){
      //initializing是为了解决我们之前说的继承导致原型有多余参数的问题。当我们直接将父类的实例赋值给子类原型时。是会调用一次父类的构造函数的。所以这边会把真正的构造流程放到init函数里面,通过initializing来表示当前是不是处于构造原型阶段,为true的话就不会调用init。
      //fnTest用来匹配代码里面有没有使用super关键字。对于一些浏览器`function(){xyz;}`会生成个字符串,并且会把里面的代码弄出来,有的浏览器就不会。`/xyz/.test(function(){xyz;})`为true代表浏览器支持看到函数的内部代码,所以用`/\b_super\b/`来匹配。如果不行,就不管三七二十一。所有的函数都算有super关键字,于是就是个必定匹配的正则。
      var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
     
      // The base Class implementation (does nothing)
      // 超级父类
      this.Class = function(){};
     
      // Create a new Class that inherits from this class
      // 生成一个类,这个类会具有extend方法用于继续继承下去
      Class.extend = function(prop) {
        //保留当前类,一般是父类的原型
        //this指向父类。初次时指向Class超级父类
        var _super = this.prototype;
       
        // Instantiate a base class (but only create the instance,
        // don't run the init constructor)
        //开关 用来使原型赋值时不调用真正的构成流程
        initializing = true;
        var prototype = new this();
        initializing = false;
       
        // Copy the properties over onto the new prototype
        for (var name in prop) {
          // Check if we're overwriting an existing function
          //这边其实就是很简单的将prop的属性混入到子类的原型上。如果是函数我们就要做一些特殊处理
          prototype[name] = typeof prop[name] == "function" &&
            typeof _super[name] == "function" && fnTest.test(prop[name]) ?
            (function(name, fn){
              //通过闭包,返回一个新的操作函数.在外面包一层,这样我们可以做些额外的处理
              return function() {
                var tmp = this._super;
               
                // Add a new ._super() method that is the same method
                // but on the super-class
                // 调用一个函数时,会给this注入一个_super方法用来调用父类的同名方法
                this._super = _super[name];
               
                // The method only need to be bound temporarily, so we
                // remove it when we're done executing
                //因为上面的赋值,是的这边的fn里面可以通过_super调用到父类同名方法
                var ret = fn.apply(this, arguments);  
                //离开时 保存现场环境,恢复值。
                this._super = tmp;
               
                return ret;
              };
            })(name, prop[name]) :
            prop[name];
        }
       
        // 这边是返回的类,其实就是我们返回的子类
        function Class() {
          // All construction is actually done in the init method
          if ( !initializing && this.init )
            this.init.apply(this, arguments);
        }
       
        // 赋值原型链,完成继承
        Class.prototype = prototype;
       
        // 改变constructor引用
        Class.prototype.constructor = Class;
     
        // 为子类也添加extend方法
        Class.extend = arguments.callee;
       
        return Class;
      };
    })();
    
    ShowPipeList = ListPager.extend({
    	
    	init : function(container, primaryKey, url){
    		debugger;
    		//列表容器
    		this.container = container;
    		//主键字段
    		this.primaryKey = primaryKey;
    		//数据请求地址
    		this.url = url;
    		//界面需要引用的插件
    		this.plugins = ['table', 'element', 'form', 'laydate', 'layer','carousel'];
    //		//弹出卡片界面的大小[60%,80%]
    //		this.cardSize = ['100%','100%'];
    //		//弹出卡片界面方式:页面层(这里content是一个普通的String):1;iframe层(content是一个URl):2
    		this.cardPopStyle = 2;
    		//每页大小 
    		this.pageSize = 5;
    		//列表头
    		this.title = [[
    			{field: 'checkDate', title: '运行日期', width: 160},
    			
    			{field: 'userRegion', title: '用户区域', width: 160},
    			
    			{field: 'runUser', title: '运行人员', width: 160},
    			
    			{field: 'dayCovRate', title: '党日覆盖率', width: 160},
    			
    			{field: 'cycleCovRate', title: '周期覆盖率', width: 160},
    			
    			{field: 'startTime', title: '开始时间', width: 160},
    			
    			{field: 'endTime', title: '结束时间', width: 160},
    			
    			{field: 'organization', title: '部门', width: 160},
    			
    			{fixed: 'right', title: '轨迹查看', align:'center',width: 80, toolbar: '#scanPipe'}
    			
    	     ]]; 
    		//插件是基于layui封装的, layOption是对layui的参数扩展(具体api参照layui属性)
    		this.layOption = {
    				
    		};
    	},
    	initLayuiPlugin: function(){
    		this._super();
    		
    		  var table = layui.table;
    		  var laydate = layui.laydate;
    		    //时间选择器
    		  laydate.render({
    		    elem: '#test5'
    		    ,type: 'time'
    		    ,theme: '#050a3c'
    		  });
    		  
    		  laydate.render({
    			    elem: '#test6'
    			    ,type: 'time'
    			    ,theme: '#050a3c'
    		});
    	},
    	initEvent: function(){
    		this._super();
    		//TODO 父类仅仅绑定了工具条通用按钮事件, 如有其他事件请在这里定义
    	},
    	hookMethod:function(obj){
    		
    	 	var data = obj.data,
    	 	url = CONTEXT_PATH + '/cusviews/pipe/listPipePoint';
    		var param = {
    				cobwebId : data.cobwebId
    		}
    		var retData = $.getData(url,param);
    		if(1000 != retData.status){
    			layer.msg('获取数据失败', {icon: 5});
    			return;
    		}
    		var points = [];
    		pipe.removePoint();
    		pipe.removeLine();
    		pipe.closeInfoWindow();
    		var data = retData.data;
    		if(!$.isEmptyArray(data)){
    			for(var i=0;i");
    				   info.push("
    "); /*info.push("
    "+userArea+"
    ");*/ info.push("
    "); info.push("
    "); info.push("
    "); info.push("
    "); info.push("

    开始时间:"+ data[i].startTime +"

    "); info.push("

    结束时间:"+ data[i].endTime +"

    "); info.push("

    检测人 :"+data[i].checkUser +"

    "); drawPoint.type["infowindow"] ={ content: info.join(""), xoffset: 0, yoffset:-31, width:360, height:100 }; drawPoint.type["onClick"] = function(point, e,i){ pipe.showInfoWindow(point); } if(0 == i||(data.length - 1) == i){ pipe.drawPoint(drawPoint); } } pipe.drawLine(points); } } }); $(function(){ var url = CONTEXT_PATH + '/cusviews/pipe/listPipe'; var showPipeList = new ShowPipeList("pipeList", "cobwebId", url); showPipeList.render(); $(".tc_box .cbar").scrollBar(); })

    layui框架使用与代码编写_第6张图片

    layui框架使用与代码编写_第7张图片

    layui框架使用与代码编写_第8张图片

    layui框架使用与代码编写_第9张图片

    layui框架使用与代码编写_第10张图片

    layui框架使用与代码编写_第11张图片

    layui框架使用与代码编写_第12张图片

    layui框架使用与代码编写_第13张图片

    layui框架使用与代码编写_第14张图片

    layui框架使用与代码编写_第15张图片

    layui框架使用与代码编写_第16张图片

    layui框架使用与代码编写_第17张图片

    layui框架使用与代码编写_第18张图片

    layui框架使用与代码编写_第19张图片

    layui框架使用与代码编写_第20张图片

    layui框架使用与代码编写_第21张图片

    layui框架使用与代码编写_第22张图片

    layui框架使用与代码编写_第23张图片

    layui框架使用与代码编写_第24张图片

    layui框架使用与代码编写_第25张图片

    layui框架使用与代码编写_第26张图片

    layui框架使用与代码编写_第27张图片

    layui框架使用与代码编写_第28张图片

    layui框架使用与代码编写_第29张图片

    layui框架使用与代码编写_第30张图片

    layui框架使用与代码编写_第31张图片

    layui框架使用与代码编写_第32张图片

    layui框架使用与代码编写_第33张图片

    layui框架使用与代码编写_第34张图片

    layui框架使用与代码编写_第35张图片

    layui框架使用与代码编写_第36张图片

    layui框架使用与代码编写_第37张图片

    layui框架使用与代码编写_第38张图片

    layui框架使用与代码编写_第39张图片

    layui框架使用与代码编写_第40张图片

    layui框架使用与代码编写_第41张图片

    layui框架使用与代码编写_第42张图片

    layui框架使用与代码编写_第43张图片

    layui框架使用与代码编写_第44张图片

    layui框架使用与代码编写_第45张图片

    layui框架使用与代码编写_第46张图片

    layui框架使用与代码编写_第47张图片

    layui框架使用与代码编写_第48张图片

    layui框架使用与代码编写_第49张图片

    layui框架使用与代码编写_第50张图片

    layui框架使用与代码编写_第51张图片

    layui框架使用与代码编写_第52张图片

    layui框架使用与代码编写_第53张图片

    layui框架使用与代码编写_第54张图片

    layui框架使用与代码编写_第55张图片

    layui框架使用与代码编写_第56张图片

    layui框架使用与代码编写_第57张图片

    js模拟了java,闭包内部定义了一个'构造函数',通过实例化new this();来动态获取当前对象

     

     

     

     

     

     

     

     

     

     

     

     

    你可能感兴趣的:(如何编写)