preface

This is the 4th day of my participation in the August More Text Challenge. To meet the challenge of digging gold in August, today I would like to share some information about the classic front-end framework layui dynamic table data operation, combined with JQuery dynamic editing cell data, hoping to help people in need, come on, mutual encourage!

Style function Description

Initialization code

According to the Layui development documentation, we could easily write the following code to load the built-in components and dynamically populate the table data:

layui.use(function () { let layer = layui.layer, element = layui.element, table = layui.table, form = layui.form; // Specify edit field const field = ['typeName']; 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 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: {title:' operation ', Fixed: 'right', width: 200, align: 'center', toolbar: '#myBar'}], text: {none: 'Show a lonely oh'}}); });Copy the code

instructions

First of all, by requesting background data, the requested data is assigned by data parsing. Note: If paging is enabled, the total number of displayed items needs to be transmitted by the back end. When opening the page, the default paging request is sent. ? Page =1&limit=10, using the request attribute to change the name of the parameter passed, for example, my paging request was changed to… all? Offset = 1 & pageSize = 10.

When toolbar is enabled, the default header bar on the right is opened, and defaultToolbar property values are left blank if not required. Also, when you customize toobar, the HTML tag element must be placed inside the div tag for this to work as a rule.

Toobar uses Layui template syntax to validate the current administrator permissions, and does not display them if they are not present.

Turn on the checkbox with {type: ‘checkbox’, fixed: ‘left’} and fix it to the far left of the table.

In the action bar, introduce external custom toolbars by ID

<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 the code

Adding 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 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 to delete ID[${ids}]? 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)) { Reload the page setTimeout(function () {location.href = 'newstypelist.html '; }, delayTime); }}}); layer.close(index); }); Else {layer. MSG (' please select at least one line ', {icon: 3}); }}});Copy the code

The common js file defines serverBase (request back-end base address), delayTime (message shell delayTime), and handleResponseData, a function that encapsulates the processing of returned data. So that’s the two functions of the header toolbar, which is pretty simple, right?

Listen on the table row toolbar

Table. on('tool(newsTypeList)', function (obj) {var layEvent = obj.event; 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]} line? 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)) {setTimeout(function () {// Remove the DOM structure corresponding to the line (tr) and update the cache obj.del(); }, delayTime); }}}); layer.close(index); }); break; }});Copy the code

Row deletion is very simple, that is, click on the row to get the ID of the object to be deleted, and pass it to the back end to complete the data deletion of the corresponding row.

Inline implementation click edit button to edit is a bit difficult, first of all, when you click on the button, agreed to open the field of editing, which will appear after clicking an input box, you can modify the update operation, when the input box loses focus, and just edit entry to shut down, which is clicked again won’t appear secondary input box.

Obj.tr. Find (' [data-field$=${field[0]}] '). Data ('edit', true);Copy the code

Where, field specifies the name of the edit field, which is consistent with the value of the field attribute in the COLs attribute.

// Specify edit field const field = ['typeName'];Copy the code

{field: ‘typeName’, title: ‘news category ‘, align: {field: ‘typeName’, title:’ news category ‘; ‘center’, edit: true}

Since the input box appears after clicking the corresponding cell, a click event is registered for the cell, and the input box cannot be immediately obtained after clicking the event. DOM structure update needs to be delayed, so it is necessary to give some time to delay the acquisition.

Through browser debugging, it is found that the last child element in the parent element of the cell TD is input, and an out-of-focus event is added. When triggered, the editing entry is closed and the button needs to be pressed again to open it.

row[0].onclick = function() { setTimeout(function () { field_td[0].lastChild.onblur = function () { row.find('[data-field$=typeName]').data('edit', false); }}, 10); };Copy the code

Listening cell

Table. on('edit(newsTypeList)', function(obj) {let value = obj.value, data = obj.data; field = obj.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 the code

Finally, the modified object is passed in and the update request is sent. The modified value can be verified in the background. If the modification fails, the current page will be refreshed.

At the end

Finally,, thank you very much for reading here, your attention, comments and even praise is my unremitting motivation to study and persist!