利用jQuery实现Layui表格添加行删除保存代码



11 43 15



特效描述:利用jQuery实现 Layui 表格添加 行删除 保存代码,利用jQuery实现Layui表格添加行删除保存代码

代码结构

1. 引入CSS

<link rel="stylesheet" href="layui/css/layui.css" />
<link rel="stylesheet" href="layui/css/layui.css" />

2. 引入JS

<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
<script src="layui/layui.js?v=201805080202" charset="utf-8"></script>
<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
<script src="layui/layui.js?v=201805080202" charset="utf-8"></script>

3. HTML代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="renderer" content="webkit" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="format-detection" content="telephone=no" />
<title></title>
<!--[if lt IE 9]>
<![endif]-->
<style type="text/css">
	/*您可以将下列样式写入自己的样式表中*/
	.childBody{padding: 15px;}
	/*layui 元素样式改写*/
	.layui-btn-sm{line-height: normal; font-size: 12.5px;}		
	.layui-table-view .layui-table-body{min-height: 256px;}
	.layui-table-cell .layui-input.layui-unselect{height: 30px; line-height: 30px;}
	/*设置 layui 表格中单元格内容溢出可见样式*/
	.table-overlay .layui-table-view,
	.table-overlay .layui-table-box,
	.table-overlay .layui-table-body{overflow: visible;}
	.table-overlay .layui-table-cell{height: auto; overflow: visible;}
	/*文本对齐方式*/
	.text-center{text-align: center;}
</style>
</head>
<body class="childBody">
<section class="layui-col-md10" style="margin: 0 auto; float: none;">
	<div class="layui-card">
		<div class="layui-card-header">基于 layui table 添加一行并实现在编辑行记录后保存数据的方法</div>
		<div class="layui-card-body layui-text">
			<div id="toolbar">
				<div>
					<button type="button" class="layui-btn layui-btn-sm" data-type="addRow" title="添加一行">
						<i class="layui-icon layui-icon-add-1"></i> 添加一行
					</button>					
				</div>
			</div>
			<div id="tableRes" class="table-overlay">
				<table id="dataTable" lay-filter="dataTable" class="layui-hide"></table>
			</div>
			<div id="action" class="text-center">
				<button type="button" name="btnSave" class="layui-btn" data-type="save"><i class="layui-icon layui-icon-ok-circle"></i>保存</button>				
				<button type="reset" name="btnReset" class="layui-btn layui-btn-primary">取消</button>
			</div>
		</div>
	</div>
	<!--保存结果输出-->		
	<div class="layui-card">
		<div class="layui-card-header">保存结果输出</div>			
		<div class="layui-card-body layui-text">						
			<blockquote class="layui-elem-quote layui-quote-nm">
				<pre id="jsonResult"><span class="layui-word-aux">请点击“保存”后查看输出信息……</span></pre>
			</blockquote>
		</div>
	</div>
</section>
<!--recommended script position-->
<script type="text/javascript">
	//准备视图对象
	window.viewObj = {
		tbData: [{
			tempId: new Date().valueOf(),
			type: 2,
			name: '测试项名称',
			state: 1
		}],
		typeData: [
			{id: 1, name: '分类一'},
			{id: 2, name: '分类二'},
			{id: 3, name: '分类三'},
			{id: 4, name: '分类四'}
		],
		renderSelectOptions: function(data, settings){
			settings =  settings || {};
			var valueField = settings.valueField || 'value',
				textField = settings.textField || 'text',
				selectedValue = settings.selectedValue || "";
			var html = [];
			for(var i=0, item; i < data.length; i++){
				item = data[i];
				html.push('<option value="');
				html.push(item[valueField]);
				html.push('"');
				if(selectedValue && item[valueField] == selectedValue ){						
					html.push(' selected="selected"');
				}			
				html.push('>');		
				html.push(item[textField]);
				html.push('</option>');
			}
			return html.join('');
		}
	};
	//layui 模块化引用
	layui.use(['jquery', 'table', 'layer'], function(){
		var $ = layui.$, table = layui.table, form = layui.form, layer = layui.layer;
		//数据表格实例化			
		var tbWidth = $("#tableRes").width();
		var layTableId = "layTable";
		var tableIns = table.render({
			elem: '#dataTable',
			id: layTableId,
			data: viewObj.tbData,
			width: tbWidth,
			page: true,
			loading: true,
			even: false, //不开启隔行背景
			cols: [[
				{title: '序号', type: 'numbers'},
				{field: 'type', title: '分类(type)', templet: function(d){
					var options = viewObj.renderSelectOptions(viewObj.typeData, {valueField: "id", textField: "name", selectedValue: d.type});
					return '<a lay-event="type"></a><select name="type" lay-filter="type"><option value="">请选择分类</option>' + options + '</select>';
				}},
				{field: 'name', title: '名称(name)', edit: 'text'},
				{field: 'state', title: '是否启用(state)', event: 'state', templet: function(d){
					var html = ['<input type="checkbox" name="state" lay-skin="switch" lay-text="是|否"'];
					html.push(d.state > 0 ? ' checked' : '');
					html.push('>');
					return html.join('');
				}},					
				{field: 'tempId', title: '操作', templet: function(d){
					return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="'+ d.tempId +'"><i class="layui-icon layui-icon-delete"></i>移除</a>';
				}}
			]],
			done: function(res, curr, count){
				viewObj.tbData = res.data;
			}
		});
		//定义事件集合
		var active = {
			addRow: function(){	//添加一行
				var oldData = table.cache[layTableId];
				console.log(oldData);
				var newRow = {tempId: new Date().valueOf(), type: null, name: '请填写名称', state: 0};
				oldData.push(newRow);
				tableIns.reload({
					data : oldData
				});
			},
			updateRow: function(obj){
				var oldData = table.cache[layTableId];				
				console.log(oldData);
				for(var i=0, row; i < oldData.length; i++){
					row = oldData[i];
					if(row.tempId == obj.tempId){
						$.extend(oldData[i], obj);
						return;
					}
				}
				tableIns.reload({
					data : oldData
				});
			},
			removeEmptyTableCache: function(){
				var oldData = table.cache[layTableId];		
				for(var i=0, row; i < oldData.length; i++){
					row = oldData[i];
					if(!row || !row.tempId){
						oldData.splice(i, 1);    //删除一项
					}
					continue;
				}
				tableIns.reload({
					data : oldData
				});
			},
			save: function(){
				var oldData = table.cache[layTableId];	
				console.log(oldData);	
				for(var i=0, row; i < oldData.length; i++){
					row = oldData[i];
					if(!row.type){
						layer.msg("检查每一行,请选择分类!", { icon: 5 }); //提示
						return;
					}
				}
				document.getElementById("jsonResult").innerHTML = JSON.stringify(table.cache[layTableId], null, 2);	//使用JSON.stringify() 格式化输出JSON字符串		
			}
		}
		//激活事件
		var activeByType = function (type, arg) {
			if(arguments.length === 2){					
				active[type] ? active[type].call(this, arg) : '';
			}else{
				active[type] ? active[type].call(this) : '';
			}
		}
		//注册按钮事件
		$('.layui-btn[data-type]').on('click', function () {
			var type = $(this).data('type');
			activeByType(type);
		});
		//监听select下拉选中事件
		form.on('select(type)', function(data){
			var elem = data.elem; //得到select原始DOM对象
			$(elem).prev("a[lay-event='type']").trigger("click");
		});
		 //监听工具条
		table.on('tool(dataTable)', function (obj) {
			var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
			console.log(data);
			switch(event){
				case "type":
					//console.log(data);
					var select = tr.find("select[name='type']");
					if(select){						
						var selectedVal = select.val();
						if(!selectedVal){
							layer.tips("请选择一个分类", select.next('.layui-form-select'), { tips: [3, '#FF5722'] }); //吸附提示
						}
						console.log(selectedVal);
						$.extend(obj.data, {'type': selectedVal});
						activeByType('updateRow', obj.data);	//更新行记录对象
					}
					break;
				case "state":
					var stateVal = tr.find("input[name='state']").prop('checked') ? 1 : 0;
					$.extend(obj.data, {'state': stateVal})	
					activeByType('updateRow', obj.data);	//更新行记录对象
					break;						
				case "del":
					layer.confirm('真的删除行么?', function(index){
					  obj.del(); //删除对应行(tr)的DOM结构,并更新缓存
					  layer.close(index);
					  activeByType('removeEmptyTableCache');
					});
					break;						
			}
		});
	});
</script>
<div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';">
</div>
</body>
</html>



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册


热门标签: 切换按钮 表单 表单美化 表单插件 表单美化插件 文本框 text文本框 下拉框 select下拉菜单 select美化 select美化框 按钮控制 添加删除

×
×

注册

官方QQ群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到