Moving a table using jQuery

I have a table with an HTML attribute in a TR element called "data order", which simply contains an integer indicating the sort order of the table (descending). Right now, the code only checks a row before pressing TR - what I'm trying to do is make it scan all the rows in front of its position in the table and as soon as it finds a number greater than (not greater than or equal to), then call the swaprow function ...

Here is the javascript used to move the line up.

function adjustRank(id, e) { var url = "/ajax/moveup/" + aid; var row = $(e).closest("tr").get(0); var prevRow = $(row).prev().get(0); var moveUp = false; var prevRowOrder = parseInt($(prevRow).attr("data-order")); var rowOrder = parseInt($(row).attr("data-order")); $.ajax({ type: "POST", url: url, data: {aid: aid}, dataType: "json", success: function () { if(rowOrder + 1 > prevRowOrder) // think this is where I need to traverse the table swapRows(row, prevRow); }, failure: function () { alert("Error processing request."); } }); } 

and here are a couple of elements in the table, for example:

 <table id="listings" style="min-height:150px; width:100%;"> <tr id="1" data-order="11"><td>1</td><td align="left"><span onclick="adjustRank('ace93485-cea5-4243-8294-9f3d009aba3d', this)" style="cursor:pointer;">Lindsey Vonn</span></td><td></td></tr> <tr id="2" data-order="6"><td>2</td><td align="left"><span onclick="adjustRank('9f83aed6-b99a-4674-a8b7-9f3d009aba38', this)" style="cursor:pointer;">Al Horford</span></td><td></td></tr> <tr id="3" data-order="5"><td>3</td><td align="left"><span onclick="adjustRank('d48a52bd-17e9-4631-9a2e-9f3d009aba39', this)" style="cursor:pointer;">Derek Jeter</span></td><td></td></tr> </table> 
+4
source share
1 answer

You can use recursion to solve this problem. Please see the code.

 window.adjustRank = function(id, el) { var orderDiff = 1; var row = $(el).closest("tr"); var order = parseInt(row.attr("data-order")) + orderDiff; row.attr("data-order", order); var prevRow = row.prev(); if(prevRow.get(0)){ moveUp(order, row, prevRow); } } window.moveUp = function(order, row, prevRow){ if(order > parseInt(prevRow.attr("data-order"))){ var prevPrevRow = prevRow.prev(); if(prevPrevRow.get(0)){ moveUp(order, row, prevPrevRow); } else { prevRow.before(row); } } else { prevRow.after(row); } } 

If you get orderDiff via AJAX, put the code in the function of a successful AJAX call. Please see this demo.

+2
source

Source: https://habr.com/ru/post/1381827/


All Articles