「前端开发」前端表格在线编辑组件:Tabulater.js 入门和熟练使用教程案例

一、简介

易于使用、易于编码、功能齐全、交互式 JavaScript 表格和数据网格。(哈哈,果然是简单一两句带过。)

二、简单使用

(1)前期准备

引入CDN:当然,如果你是在线上项目中使用,最好是下载下来到本地使用,而不是使用不靠谱的CDN(当然也有靠谱的CDN服务购买的哈)

html 复制代码
<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>

(2)使用三步走

【1】定义一个HTML元素
html 复制代码
<div id="example-table"></div>
【2】简单渲染只读表格:JavaScript 渲染 HTML
js 复制代码
//define data array
var tabledata = [
    {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1},
    {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true},
    {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"},
    {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"},
    {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"},
    {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1},
];

//initialize table
var table = new Tabulator("#example-table", {
    data:tabledata, //assign data to table
    autoColumns:true, //create columns from data field names
});

得到的渲染结果表格如下:(默认表格只读状态,如果需要在线编辑,请看后续详解)

【3】核心:丰富属性配置表格

在 JavaScript 中扩展对应的 tabulater.js 的配置,使得它支持 在线可编辑,可过滤筛选,删除指定行或列,增加行或列,标记渲染行或列 ,手动拖动行宽,手动调整列先后顺序等功能。

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>
	</head>
	<body>
		
		<div id="example-table"></div>
		
		<script>
			//define data array
			var tabledata = [
			    {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1},
			    {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true},
			    {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"},
			    {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"},
			    {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"},
			    {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1},
			];
			
			var table = new Tabulator("#example-table", {
			    data:tabledata,           //加载数据
			    layout:"fitColumns",      //根据表格宽度调整列
			    responsiveLayout:"hide",  //隐藏不适合放在table上的列
			    addRowPos:"top",          //添加新行时,将其添加到表的顶部
			    history:true,             //允许对表执行撤消和重做操作
			    pagination:"local",       //对数据进行分页
			    paginationSize:5,         //每页允许5行数据
			    paginationCounter:"rows", //页脚中分页行的显示计数
			    movableColumns:true,      //允许更改列顺序
			    initialSort:[             //设置数据的初始排序顺序
			        {column:"name", dir:"asc"},
			    ],
			    columnDefaults:{
			        tooltip:true,         //在单元格上显示工具提示
			    },
			    columns:[                 //定义表格列属性和配置
					//名字列:输入文本类型 
			        {title:"Name", field:"name", editor:"input"},
					//任务进度列:进度条类型,靠左,可编辑(方向键调整进度,enter键情况了)
			        {title:"Task Progress", field:"progress", hozAlign:"left", formatter:"progress", editor:true},
					//性别列:下拉选择,定义枚举类型
			        {title:"Gender", field:"gender", width:95, editor:"select", editorParams:{values:["male", "female"]}},
					//评级列:星级评定,可设置宽度,是否可编辑,默认五星
			        {title:"Rating", field:"rating", formatter:"star", hozAlign:"center", width:100, editor:true},
					//颜色:输入框,定义固定宽度
			        {title:"Color", field:"col", width:130, editor:"input"},
					// 出生日期:日期类型,显示居中
			        {title:"Date Of Birth", field:"dob", width:130, sorter:"date", hozAlign:"center"},
					// 是否:判断类型,宽度,格式化正确错误标记
			        {title:"Driver", field:"car", width:90,  hozAlign:"center", formatter:"tickCross", sorter:"boolean", editor:true},
			    ],
			});
		</script>
	</body>
</html>

案例显示结果如下:

三、详细讲解

(1)列表分页配置

关键分页的属性

  1. 【pagination: "local" 】启用本地所有数据进行分页功能;
  2. 【paginationSize:3】初始化数据显示的每一页的数量;
  3. 【paginationSelector:[3,6,810]】可选的每页显示的数量;

实例完整源码

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>

	</head>
	<body>
		<div id="example-table"></div>
		
		<script type="text/javascript">
			var tabledata = [
			    {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1},
			    {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true},
			    {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"},
			    {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"},
			    {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"},
			    {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1},
			];
			
			//Build Tabulator
			var table = new Tabulator("#example-table", {
				data: tabledata,
			    layout:"fitColumns",
				
				// 分页属性 --- start
			    pagination:"local", // 启用分页
			    paginationSize:3, // 初始分页数量
			    paginationSizeSelector:[3, 6, 8, 10],// 可选分页数量
				// 分页属性 --- end
				
			    movableColumns:true,
			    paginationCounter:"rows",
			    columns:[
			        {title:"Name", field:"name", width:200},
			        {title:"Progress", field:"progress", formatter:"progress", sorter:"number"},
			        {title:"Gender", field:"gender"},
			        {title:"Rating", field:"rating", formatter:"star", hozAlign:"center", width:100},
			        {title:"Favourite Color", field:"col"},
			        {title:"Date Of Birth", field:"dob", hozAlign:"center", sorter:"date"},
			        {title:"Driver", field:"car", hozAlign:"center", formatter:"tickCross"},
			    ],
			});
		</script>
	</body>
</html>

(2)筛选过滤

四种过滤方式:

  1. 初始化过滤;(数据初始化的时候按照默认的展示情况进行过滤处理)
  2. 单列过滤(过滤关键字,大于,小于,等于,大于等于,小于等于,集合,模糊匹配,不等于 等筛选操作);
  3. 多列混合过滤;(多列过滤,例如,成绩及格的并且是一班的学生的数据)
  4. 并且/或者过滤;(多列过滤,使用 并且 和 或者 组合条件来进行数据上的匹配)

实例完整源码

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>过滤tabulater</title>
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>
	</head>
	<body>
		
		<div>
		  <select id="filter-field">
		    <option></option>
		    <option value="name">Name</option>
		    <option value="progress">Progress</option>
		    <option value="gender">Gender</option>
		    <option value="rating">Rating</option>
		    <option value="col">Favourite Colour</option>
		    <option value="dob">Date Of Birth</option>
		    <option value="car">Drives</option>
		    <option value="function">Drives & Rating < 3</option>
		  </select>
		
		  <select id="filter-type">
		    <option value="=">=</option>
		    <option value="<"><</option>
		    <option value="<="><=</option>
		    <option value=">">></option>
		    <option value=">=">>=</option>
		    <option value="!=">!=</option>
		    <option value="like">like</option>
		  </select>
		
		  <input id="filter-value" type="text" placeholder="value to filter">
		
		  <button id="filter-clear">Clear Filter</button>
		</div>
		
		<div id="example-table"></div>
	</body>
	
	<script type="text/javascript">
		
		var tabledata = [
		    {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1},
		    {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true},
		    {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"},
		    {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"},
		    {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"},
		    {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1},
		];
		
		//Define variables for input elements
		var fieldEl = document.getElementById("filter-field");
		var typeEl = document.getElementById("filter-type");
		var valueEl = document.getElementById("filter-value");
		
		//Custom filter example
		function customFilter(data){
		    return data.car && data.rating < 3;
		}
		
		//Trigger setFilter function with correct parameters
		function updateFilter(){
			var filterVal = fieldEl.options[fieldEl.selectedIndex].value;
			var typeVal = typeEl.options[typeEl.selectedIndex].value;
		
			var filter = filterVal == "function" ? customFilter : filterVal;
		
			if(filterVal == "function" ){
				typeEl.disabled = true;
				valueEl.disabled = true;
			}else{
				typeEl.disabled = false;
				valueEl.disabled = false;
			}
		
			if(filterVal){
				table.setFilter(filter,typeVal, valueEl.value);
			}
		}
		
		//Update filters on value change
		document.getElementById("filter-field").addEventListener("change", updateFilter);
		document.getElementById("filter-type").addEventListener("change", updateFilter);
		document.getElementById("filter-value").addEventListener("keyup", updateFilter);
		
		//Clear filters on "Clear Filters" button click
		document.getElementById("filter-clear").addEventListener("click", function(){
		  fieldEl.value = "";
		  typeEl.value = "=";
		  valueEl.value = "";
		
		  table.clearFilter();
		});
		
		//Build Tabulator
		var table = new Tabulator("#example-table", {
			data: tabledata,
			layout:"fitColumns",      //根据表格宽度调整列
			pagination:"local",       //对数据进行分页
			paginationSize:10,         //每页允许5行数据
		    // height:"311px",
		    layout:"fitColumns",
			initialSort:[             //设置数据的初始排序顺序
			    {column:"name", dir:"asc"},
			],
			// 筛选4:初始化过滤
			// initialFilter:[
			// 	{field:"col", type:"=", value:"red"}
			// ],
		    columns:[
		        {title:"Name", field:"name", width:200},
		        {title:"Progress", field:"progress", formatter:"progress", sorter:"number"},
		        {title:"Gender", field:"gender"},
		        {title:"Rating", field:"rating", formatter:"star", hozAlign:"center", width:100},
		        {title:"Favourite Color", field:"col"},
		        {title:"Date Of Birth", field:"dob", hozAlign:"center", sorter:"date"},
		        {title:"Driver", field:"car", hozAlign:"center", formatter:"tickCross"},
		    ],
		});
		// 筛选1:单列筛选:
		// 初始化筛选1:比例>2的进行显示
		// table.setFilter("rating", ">", 2);
		// 初始化筛选2:field是 col 的,关键字包含 red/green/blue 所有的进行展示
		// table.setFilter("col", "keywords", "red green blue", {matchAll:false});
		
		// 筛选2:多列符合筛选
		// table.setFilter([
			// {field: "rating", type: ">=", value: 2},
			// {field: "rating", type: ">", value: 2},
			// {field: "rating", type: "=", value: 2},
			// {field: "rating", type: "!=", value: 2},
			// {field: "rating", type: "<", value: 2},
			// {field: "rating", type: "<=", value: 2},
			// {field: "name", type: "like", value: "ob"},
			// {field: "name", type: "regex", value: /[a-z]/},
			// {field: "col", type: "in", value: ["red","green","blue"]},
		// ])
		
		// 筛选3:自定义筛选 customFilter: 符合筛选(名称中包含"ob"并且评星小于1)的数据
		// function customFilter(data, filterParams){
		//     //data - the data for the row being filtered
		//     //filterParams - params object passed to the filter
		
		// 	//must return a boolean, true if it passes the filter.
		//     return data.name.includes("ob") && data.rating < filterParams.rating;
		// }
		// table.setFilter(customFilter, {rating:1});
		
	</script>
</html>

(3)AJAX 获取动态数据

注意事项:

  1. 定义后端好返回的数据接口;
  2. 前端JavaScript 提前定义好对应的列表头和对应的列属性;

完整实例代码

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>
		
	</head>
	<body>
		<div>
		    <button id="ajax-trigger">Load Data via AJAX</button>
		</div>
		
		<div id="example-table"></div>
	</body>
	
	<script type="text/javascript">
		//1.构建在线表格组件库 tabulator
		var table = new Tabulator("#example-table", {
		    height:"311px",
		    layout:"fitColumns",
		    placeholder:"No Data Set", // 默认无数据的时候显示内容
		    columns:[
		        {title:"Name", field:"name", sorter:"string", width:200},
		        {title:"Progress", field:"progress", sorter:"number", formatter:"progress"},
		        {title:"Gender", field:"gender", sorter:"string"},
		        {title:"Rating", field:"rating", formatter:"star", hozAlign:"center", width:100},
		        {title:"Favourite Color", field:"col", sorter:"string"},
		        {title:"Date Of Birth", field:"dob", sorter:"date", hozAlign:"center"},
		        {title:"Driver", field:"car", hozAlign:"center", formatter:"tickCross", sorter:"boolean"},
		    ],
		});
		
		//trigger AJAX load on "Load Data via AJAX" button click
		document.getElementById("ajax-trigger").addEventListener("click", function(){
			// 1.此处使用 AJAX 的请求方式,调用远程的接口来得到对应的数据
			// 2.讲数据存入到data数据中
		    table.setData("/exampledata/ajax");
		});
	</script>
</html>

(4)导入模版文件数据

前期模版数据如下,可以自己准备些数据到 Excel / csv 文件中哈。

Name Favourite Cheese Cars Age Favourite Colour
Steve brie volvo 23 red
Bob cheddar bmw 24 green
Sandra gouda ford 36 blue
Jim cheddar mercedes 52 green
Jessica edam ford 19 green
Frank brie volvo 48 red

CSV 文件格式的数据如下:(①新建一个txt文本文件;②放入下方数据;③改文件后缀为 .csv 文件)

csv 复制代码
Name,Favourite,Cheese,Cars,Age,Favourite Colour
Steve,brie,volvo,23,red
Bob,cheddar,bmw,24,green
Sandra,gouda,ford,36,blue
Jim,cheddar,mercedes,52,green
Jessica,edam,ford,19,green
Frank,brie,volvo,48,red

完整代码示例

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet"> 
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>
	</head>
	<body>
		<div>
			<button id="file-load-trigger">选择文件(excel/csv/ods)</button>
		</div>

		<div id="example-table"></div>
	</body>

	<script type="text/javascript">
		//1.定义tabulator
		var table = new Tabulator("#example-table", {
			height: 311,
			layout: "fitColumns",
			autoColumns: true,
			placeholder: "Awaiting Data, Please Load File",
		});
		// 2.定义文件类型
		document.getElementById("file-load-trigger").addEventListener("click", function() {
			table.import("xlsx", [".xlsx", ".csv", ".ods"], "buffer");
		});
	</script>
</html>

展示结果:

(5)表格数据指定属性分组

分组属性:

  • 【groupBy:"gender"】即可,指定某一列属性即可,至于你想 多维属性 分组,你自己找找官网哦。
  • 分组属性学习传送门:Examples | Tabulator

完整代码示例

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>数据分组</title>
		<!-- <link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet"> -->
		<!-- 简单主题风格 -->
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator_simple.min.css" rel="stylesheet"> 
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>
	</head>
	<body>
		
		<div id="example-table"></div>
		
		<script>
			//1.初始化的数据
			var tabledata = [
			    {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1},
			    {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true},
			    {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"},
			    {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"},
			    {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"},
			    {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1},
			    {id:7, name:"Frank Harbours", progress:38, gender:"unknown", rating:4, col:"red", dob:"12/05/1966", car:1},
			];
			// 2.定义前端表格组件
			var table = new Tabulator("#example-table", {
				data: tabledata,
			    height:"311px",
			    layout:"fitColumns",
			    movableRows:true,
			    groupBy:"gender",// 【核心】配置分组属性内容
				headerVisible:true, // [扩展]隐藏表头显示
			    columns:[
			        {title:"Name", field:"name", width:200},
			        {title:"Progress", field:"progress", formatter:"progress", sorter:"number"},
			        {title:"Gender", field:"gender", hiddenColumn:true},
			        {title:"Rating", field:"rating", formatter:"star", hozAlign:"center", width:100},
			        {title:"Favourite Color", field:"col"},
			        {title:"Date Of Birth", field:"dob", hozAlign:"center", sorter:"date"},
			        {title:"Driver", field:"car", hozAlign:"center", formatter:"tickCross"},
			    ],
			});
		</script>
	</body>
</html>

结果展示:

(6)国际化配置语言

官方配置学习传送门:Examples | Tabulator

本实例讲解了一下几点:

  1. 国际化需要手动一个属性一个属性的配置对应语言;
  2. 如果开启了总数显示,该如何设置对应属性呢?(如下示例结果图标记问题)

配置完整代码展示如下:

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>
	</head>
	<body>
		
		<div>
		    <button id="lang-french">法语</button>
		    <button id="lang-german">德语</button>
		    <button id="lang-chinese">中文</button>
		    <button id="lang-default">默认(英语)</button>
		</div>
		
		<div id="example-table"></div>
		
		<script>
			//define data array
			var tabledata = [
			    {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1},
			    {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true},
			    {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"},
			    {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"},
			    {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"},
			    {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1},
			];
			
			//Build Tabulator
			var table = new Tabulator("#example-table", {
				data: tabledata,
			    height:"141px",
			    pagination:"local",
				paginationSize:2,
				paginationSizeSelector:[2, 3, 10],
				paginationCounter:"rows", // 这个开启之后在国际化之后,国际化如何处理呢?
			    layout:"fitColumns",
			    langs:{
			        "fr-fr":{ //法语
			            "columns":{
			                "name":"Nom",
			                "progress":"Progression",
			                "gender":"Genre",
			                "rating":"Évaluation",
			                "col":"Couleur",
			                "dob":"Date de Naissance",
			            },
			            "pagination":{
			                "first":"Premier",
			                "first_title":"Première Page",
			                "last":"Dernier",
			                "last_title":"Dernière Page",
			                "prev":"Précédent",
			                "prev_title":"Page Précédente",
			                "next":"Suivant",
			                "next_title":"Page Suivante",
			                "all":"Toute",
			            },
			        },
			        "de-de":{ //德语
			            "columns":{
			                "name":"Name",
			                "progress":"Fortschritt",
			                "gender":"Genre",
			                "rating":"Geschlecht",
			                "col":"Farbe",
			                "dob":"Geburtsdatum",
			            },
			            "pagination":{
			                "first":"Erste",
			                "first_title":"Erste Seite",
			                "last":"Letzte",
			                "last_title":"Letzte Seite",
			                "prev":"Vorige",
			                "prev_title":"Vorige Seite",
			                "next":"Nächste",
			                "next_title":"Nächste Seite",
			                "all":"Alle"
			            },
			        },
					"ch-zh":{ //中文
					    "columns":{
					        "name":"姓名",
					        "progress":"进度",
					        "gender":"性别",
					        "rating":"比例",
					        "col":"颜色",
					        "dob":"出生日期",
					    },
					    "pagination":{
					        "first":"第一页",
					        "first_title":"第一页标题",
					        "last":"最后一页",
					        "last_title":"最后一页标题",
					        "prev":"前一页",
					        "prev_title":"前一页标题",
					        "next":"下一页",
					        "next_title":"下一页标题",
							"page_size": "当页显示数",
					        "all":"所有"
					    },
					},
			    },
			    columns:[
			        {title:"Name", field:"name"},
			        {title:"Progress", field:"progress", sorter:"number"},
			        {title:"Gender", field:"gender"},
			        {title:"Rating", field:"rating"},
			        {title:"Favourite Color", field:"col"},
			        {title:"Date Of Birth", field:"dob"},
			    ],
			});
			
			//set locale to French
			document.getElementById("lang-french").addEventListener("click", function(){
			    table.setLocale("fr-fr");
			});
			
			//set locale to German
			document.getElementById("lang-german").addEventListener("click", function(){
			    table.setLocale("de-de");
			});
			//set locale to Chinses
			document.getElementById("lang-chinese").addEventListener("click", function(){
			    table.setLocale("ch-zh");
			});
			//set default locale
			document.getElementById("lang-default").addEventListener("click", function(){
			    table.setLocale("");
			});
		</script>
	</body>
</html>

结果显示:

根据官方文档,查看文档(Localization | Tabulator)可知,可以一一配置单词显示的哦。下面是详细的 分页属性汉化的对应属性名。

js 复制代码
var table = new Tabulator("#example-table", {
    locale:true,
    langs:{
        "en-gb":{
            "columns":{
                "name":"Name", //replace the title of column name with the value "Name"
            },
            "data":{
                "loading":"Loading", //data loader text
                "error":"Error", //data error text
            },
            "groups":{ //copy for the auto generated item count in group header
                "item":"item", //the singular  for item
                "items":"items", //the plural for items
            },
            "pagination":{
                "page_size":"Page Size", //label for the page size select element
                "page_title":"Show Page",//tooltip text for the numeric page button, appears in front of the page number (eg. "Show Page" will result in a tool tip of "Show Page 1" on the page 1 button)
                "first":"First", //text for the first page button
                "first_title":"First Page", //tooltip text for the first page button
                "last":"Last",
                "last_title":"Last Page",
                "prev":"Prev",
                "prev_title":"Prev Page",
                "next":"Next",
                "next_title":"Next Page",
                "all":"All",
                "counter":{
                    "showing": "Showing",
                    "of": "of",
                    "rows": "rows",
                    "pages": "pages",
                }
            },
            "headerFilters":{
                "default":"filter column...", //default header filter placeholder text
                "columns":{
                    "name":"filter name...", //replace default header filter text for column name
                }
            }
        }
    },
});

(7)回调函数:处理数据之后给到后端服务接口

官方示例:Examples | Tabulator

官方文档:Callbacks | Tabulator

完整示例代码

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>

	</head>
	<body>
		<div id="example-table"></div>
		
		<script type="text/javascript">
			var tabledata = [
			    {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1},
			    {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true},
			    {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"},
			    {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"},
			    {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"},
			    {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1},
			];
			
			//Build Tabulator
			var table = new Tabulator("#example-table", {
				data: tabledata,
			    layout:"fitColumns",		
			    movableColumns:true,
			    paginationCounter:"rows",
			    columns:[
			        {title:"Name", field:"name", width:200, cellClick:function(e, cell){
						//e - the click event object
						//cell - cell component
						console.log("db click.");
						console.log(e, cell)
						console.log("单元格初始值值为:", cell._cell.initialValue)
						console.log("单元格的旧值为:", cell._cell.oldValue)
						console.log("单元格的值为:", cell._cell.value)
					},},
			        {title:"Progress", field:"progress", formatter:"progress", sorter:"number"},
			        {title:"Gender", field:"gender"},
			        {title:"Rating", field:"rating", formatter:"star", edit:true, hozAlign:"center", width:100},
			        {title:"Favourite Color", field:"col"},
			        {title:"Date Of Birth", field:"dob", hozAlign:"center", sorter:"date"},
			        {title:"Driver", field:"car", hozAlign:"center", formatter:"tickCross"},
			    ],
			});
			
			table.on("rowClick", function(e, row){
			    alert("Row " + row.getIndex() + " Clicked!!!!")
			});
			table.on("rowContext", function(e, row){
			    alert("Row " + row.getIndex() + " Context Clicked!!!!")
				// e.preventDefault();
			});
		</script>
	</body>
</html>

结果如下

(8)合计汇总行计算

官方示例:Examples | Tabulator

官方文档:Column Calculations | Tabulator

完整代码示例:

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
		<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>
		
	</head>
	<body>
		<div id="example-table"></div>
		<script type="text/javascript">
			var tabledata = [
			    {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1},
			    {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true},
			    {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"},
			    {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"},
			    {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"},
			    {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1},
			];
			
			//Build Tabulator
			var table = new Tabulator("#example-table", {
				data: tabledata,
			    layout:"fitColumns",		
			    movableColumns:true,
			    paginationCounter:"rows",
			    columns:[
			        {title:"Name", field:"name", width:200},
			        {title:"Progress", field:"progress", formatter:"input", sorter:"number",
					// 方式1:放置于汇总的数据于第一行。
						// topCalc:"avg", topCalcParams:{precision:4, /*有效位数 */ } // 计算平均值
						// topCalc:"sum", topCalcParams:{precision:0, /*有效位数 */ } // 计算总和
						// topCalc:"max", topCalcParams:{precision:0, /*有效位数 */ } // 计算最大值
						// topCalc:"min", topCalcParams:{precision:0, /*有效位数 */ } // 计算最小值
						// topCalc:"count", topCalcParams:{precision:0, /*有效位数 */ } // 提取总条目数
						// topCalc:"unique", topCalcParams:{precision:0, /*有效位数 */ } // 得到非空值(非null,非undefined,非"")的数量
						// topCalc:"concat", topCalcParams:{precision:0, /*有效位数 */ } // 此列所有值拼接
					// 方式2:放置于汇总的数据于最后一行。
						bottomCalc: "avg", bottomCalcParams: {precision:4, /*有效位数*/} ,//计算平均值
						// bottomCalc:"sum", bottomCalcParams:{precision:0, /*有效位数 */ } // 计算总和
						// bottomCalc:"max", bottomCalcParams:{precision:0, /*有效位数 */ } // 计算最大值
						// bottomCalc:"min", bottomCalcParams:{precision:0, /*有效位数 */ } // 计算最小值
						// bottomCalc:"count", bottomCalcParams:{precision:0, /*有效位数 */ } // 提取总条目数
						// bottomCalc:"unique", bottomCalcParams:{precision:0, /*有效位数 */ } // 得到非空值(非null,非undefined,非"")的数量
						// bottomCalc:"concat", bottomCalcParams:{precision:0, /*有效位数 */ } // 此列所有值拼接
					},
			        {title:"Gender", field:"gender"},
                    // 扩展学习:设置汇总行的样式如何显示?如下示例:
			        {title:"Rating", field:"rating", formatter:"star", edit:true, hozAlign:"center", width:100,
                    // 扩展1:顶部汇总样式
						// topCalc:"avg", topCalcParams:{precision:4, /*有效位数 */ }, topCalcFormatter:"star", topCalcFormatterParams:{stars:5} 
						// topCalc:"max", topCalcParams:{precision:4, /*有效位数 */ }, topCalcFormatter:"star", topCalcFormatterParams:{stars:5} 
						// topCalc:"min", topCalcParams:{precision:4, /*有效位数 */ }, topCalcFormatter:"star", topCalcFormatterParams:{stars:5} 
					// 扩展2:底部汇总样式
						// bottomCalc:"avg", bottomCalcParams:{precision:4, /*有效位数 */ }, bottomCalcFormatter: 'star', bottomCalcFormatterParams:{stars:5} // 超过5则显示满格
						// bottomCalc:"max", bottomCalcParams:{precision:0, /*有效位数 */ }, bottomCalcFormatter: 'star', bottomCalcFormatterParams:{stars:5} // 超过5则显示满格
						// bottomCalc:"min", bottomCalcParams:{precision:0, /*有效位数 */ }, bottomCalcFormatter: 'star', bottomCalcFormatterParams:{stars:5} // 超过5则显示满格
						bottomCalc:"count", bottomCalcParams:{precision:0, /*有效位数 */ }, bottomCalcFormatter: 'star', bottomCalcFormatterParams:{stars:5} // 超过5则显示满格
                    },
			        {title:"Favourite Color", field:"col"},
			        {title:"Date Of Birth", field:"dob", hozAlign:"center", sorter:"date"},
			        {title:"Driver", field:"car", hozAlign:"center", formatter:"tickCross"},
			    ],
			});
		
		</script>
	</body>
</html>

演示测试结果如下:


扩展:当然,如果需要自己定义一个计算按的函数,也是可行,这里只显示最常用的 函数哈,自定义函数传送门:【】,还有很多列计算情况,例如:① 参数查找;② 列数据分组之后的分组计算;③ 数据数计算;

附录


🙏至此,非常感谢阅读🙏

相关推荐
桃园码工16 分钟前
15_HTML5 表单属性 --[HTML5 API 学习之旅]
前端·html5·表单属性
百万蹄蹄向前冲1 小时前
2024不一样的VUE3期末考查
前端·javascript·程序员
轻口味1 小时前
【每日学点鸿蒙知识】AVCodec、SmartPerf工具、web组件加载、监听键盘的显示隐藏、Asset Store Kit
前端·华为·harmonyos
alikami1 小时前
【若依】用 post 请求传 json 格式的数据下载文件
前端·javascript·json
wakangda2 小时前
React Native 集成原生Android功能
javascript·react native·react.js
吃杠碰小鸡2 小时前
lodash常用函数
前端·javascript
emoji1111112 小时前
前端对页面数据进行缓存
开发语言·前端·javascript
泰伦闲鱼2 小时前
nestjs:GET REQUEST 缓存问题
服务器·前端·缓存·node.js·nestjs
m0_748250032 小时前
Web 第一次作业 初探html 使用VSCode工具开发
前端·html
一个处女座的程序猿O(∩_∩)O2 小时前
vue3 如何使用 mounted
前端·javascript·vue.js