我假设您要移动每个 div 以使其成为指定列的子级(而不是将其视觉定位在列上,例如 position: absolute)。
此解决方案使用一个数组,其中表中的每个 div 都有一个项目(因此 posList[0] 保存 div1 的值,postList[2] 保存 div3 的值,等等)。每个数组条目的值是一个数字,指定每个 div 的列。
/*
posList is an array specifying, for each div, the zero-based column where you want to move each div.
Example: The array [1, 3, 0] means the first div will be in column 2, the second div in column 4 and the third div in column 1 (remember that they are zero-indexed).
In this code snippet it has been hard-coded for simplicity but it should be generated from the "query of [your] database" in whatever way is appropriate to your application.
*/
var posList = [1, 3, 0]; // Hard-coded for simplicity: div1 is in col2, div2 is in col4, div3 is in col1.
var rowList = $("table tr"); // Get all the rows in the table.
var divList = rowList.find("div"); // Find all the divs in the rows. This assumes there aren't any other divs in the table at all - make this selector more specific as required).
var i = 0
,colIndex = 0
,cell = null
,div = null
,row = null;
for (i = 0; i < posList.length; i++){
colIndex = posList[i]; // Get the column index for each <div>.
if (colIndex == 0){
continue; // Minor optimisation - if the index is 0 then we don't need to move the <div>.
}
div = divList.eq(i); // The <div> that needs to be moved.
row = rowList.eq(i); // This is the <tr> element that is the ancestor of the current <div>.
cell = row.find("td").eq(colIndex); // We want to move the <div> to the <td> element specified by the column index from posList.
div.detach().appendTo(cell); // Move the <div> to the new column.
}