current position:Home>Dynamic editing of data in layui table rows
Dynamic editing of data in layui table rows
2021-08-27 07:25:56 【HUALEI】
Preface
This is my participation 8 The fourth of the yuegengwen challenge 4 God , Check out the activity details :8 Yuegengwen challenge . Coincides with the Nuggets
August is more challenging
, Today, I'd like to share some information about the classic front-end frameworklayui
Dynamic table data operation in , combinationJQuery
Dynamically edit the data in the cell , I hope I can help those in need , come on. , Mutual encouragement !
Style function description
Initialization code
according to Layui Developing documents
, We can easily write the following code , Load built-in components , Dynamic table data filling :
layui.use(function () {
let layer = layui.layer,
element = layui.element,
table = layui.table,
form = layui.form;
// Specify the edit field
const field = ['typeName'];
// Table loading data
table.render({
elem: "#newsTypeTable",
height: 522,
url: serverBase + "newsType/all",
parseData: function (res) {
return {
"code": res.code,
"data": res.data.types,
"count": res.data.count
};
},
// Open paging
page: true,
request: {
pageName: 'offset',
limitName: 'pageSize'
},
toolbar: `
<div>
{{# if(checkPermission(1, null)){ }}
<button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="add">
<i class="layui-icon layui-icon-addition"></i>
</button>
{{# } }}
{{# if(checkPermission(3, null)){ }}
<button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="batchDel">
<i class="layui-icon layui-icon-subtraction"></i>
</button>
{{# } }}
</div>
`,
defaultToolbar: [],
cols: [
[
{type: 'checkbox', fixed: 'left'},
{field: 'id', title: 'ID', sort: true, align: 'center'},
{field: 'typeName', title: ' News category ', align: 'center'},
{title: ' operation ', fixed: 'right', width: 200, align: 'center', toolbar: '#myBar'}
]
],
text: {
none: ' Show a lonely ~'
}
});
});
Copy code
explain
First, by requesting background data , Assign the requested data through data analysis , Be careful : If paging is turned on , The total number of items that need to be displayed by back-end delivery , When opening a page, the default paging request sent is ...?page=1&limit=10
, adopt request
Property to change the passed parameter name , For example, my paging request is changed to ...all?offset=1&pageSize=10
.
Open the toolbar
after , The default header toolbar on the right will open , If not, you need to defaultToolbar
Property value is empty , And when you customize toobar
when ,HTML
Label elements need to be placed in div
The Chinese side of the label can take effect , This is a rule .
toobar
Use in Layui
The template syntax verifies the current administrator permissions , If you do not have this permission, it will not be displayed .
adopt {type: 'checkbox', fixed: 'left'}
Turn on the check box , And fix it to the far left in the table .
In the operation bar , adopt id
Introduce external customization toolbar
<script type="text/html" id="myBar">
<button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="edit">
<i class="layui-icon layui-icon-edit"></i>
</button>
<button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="del">
<i class="layui-icon layui-icon-delete"></i>
</button>
</script>
Copy code
Add listening Events
Monitor header toolbar
table.on('toolbar(newsTypeList)', function(obj) {
let checkStatus = table.checkStatus(obj.config.id);
// Select row data
let selectedData = checkStatus.data;
if(obj.event === 'add') {
// Jump to the news type add page
window.open('addNewsType.html', 'mainFrame');
}else if(obj.event === 'batchDel') {
if(selectedData.length > 0) {
let ids = [];
selectedData.forEach((targetRow) => {
ids.push(targetRow.id)
});
layer.confirm(` confirm deletion ID[${ids}] Do you ?`, {title: ' Warning ', icon: 0},
function (index) {
$.ajax({
type: "DELETE",
contentType: "application/json;charset=UTF-8",
url: serverBase + "newsType/del",
data: JSON.stringify(ids),
dataType: 'json',
success: function (res) {
if (handleResponseData(res, layer)) {
// After successful deletion , Reload page
setTimeout(function () {
location.href = 'newsTypeList.html';
}, delayTime);
}
}
});
layer.close(index);
}
);
}else {
layer.msg(' Please select at least one row ', {icon: 3});
}
}
});
Copy code
public js
It's defined in the file serverBase
( Request backend base address )、delayTime
( Message layer delay time ) And encapsulating the functions that process the returned data handleResponseData
. Here we are , The two functions of the header toolbar are realized , It's a little bit easier , Right ?
Listen to the table row toolbar
table.on('tool(newsTypeList)', function (obj) {
// get lay-event Corresponding value ( It can also be in the header event The corresponding value of the parameter )
var layEvent = obj.event;
// Get the row data object
var data = obj.data;
switch (layEvent) {
case 'edit':
const row = obj.tr;
const field_td = row.find(`[data-field$=${field[0]}]`);
field_td.data('edit', true);
row[0].onclick = function() {
setTimeout(function () {
field_td[0].lastChild.onblur = function () {
row.find('[data-field$=typeName]').data('edit', false);
}
}, 10);
};
break;
case 'del':
let ids = [];
ids.push(data.id);
layer.confirm(` Really delete ID => ${ids[0]} Is it ok ?`, function(index) {
// Send delete instruction to the server
$.ajax({
type: "DELETE",
contentType: "application/json;charset=UTF-8",
url: serverBase + "newsType/del",
data: JSON.stringify(ids),
dataType: 'json',
success: function (res) {
if (handleResponseData(res, layer)) {
setTimeout(function () {
// Delete the corresponding line (tr) Of DOM structure , And update the cache
obj.del();
}, delayTime);
}
}
});
layer.close(index);
});
break;
}
});
Copy code
Line deletion is simple , Click the line to get the deleted object id
, The data of the corresponding row can be deleted by passing it to the back end .
It is a little difficult to click the Edit button to edit in the line , First you click the button , To open the edit of the contract field , That is, after clicking, an input box will appear , You can modify and update it , When the input box loses focus , Close the editing entry just now , That is, when you click again, the input box will not appear again .
// Turn on the editing of the specified field , Close the same , Parameters of the incoming false that will do
obj.tr.find(`[data-field$=${field[0]}]`).data('edit', true);
Copy code
among ,field
Specify the edit field name , and cols
Properties of the field
Property values are consistent .
// Specify the edit field
const field = ['typeName'];
Copy code
adopt JQuery
in find
Function to find the label corresponding to the cell , Re pass data
The function adds edit
attribute , And initialize it to true
value , amount to :{field: 'typeName', title: ' News category ', align: 'center', edit: true}
Because the input box appears after clicking the corresponding cell , So register a click event for the cell , You can't get... Immediately after clicking the event input
Input box , need DOM
There is a delay in updating the structure , You need to delay the acquisition time .
Found through browser debugging , This cell td
The last child element of the parent element is input
, Add out of focus event , When triggered , Close the edit entry , It is necessary to press the button again to turn on .
row[0].onclick = function() {
setTimeout(function () {
field_td[0].lastChild.onblur = function () {
row.find('[data-field$=typeName]').data('edit', false);
}
}, 10);
};
Copy code
Listen to cells
table.on('edit(newsTypeList)', function(obj) {
let value = obj.value // Get the modified value
, data = obj.data // Get all the key values of the line
, field = obj.field; // Get the modified field
let modifiedData = {id: data.id};
modifiedData[field] = value;
$.ajax({
type: "POST",
contentType: "application/json;charset=UTF-8",
url: serverBase + 'newsType/update',
data: JSON.stringify(modifiedData),
dataType: 'json',
success: function(res) {
if(!handleResponseData(res, layer)) {
setTimeout(function () {
location.href = 'newsTypeList.html';
}, delayTime);
}
}
});
});
Copy code
Last , Pass in the modified object and send an update request , The modified value can be verified in the background , If the modification fails, refresh the current page .
ending
Last , Thank you very much for seeing this , Your attention 、 Comments and even praise are my unremitting motivation for learning and persistence !!
copyright notice
author[HUALEI],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827072552415y.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich