移动HTML表格的列

时间:2018-12-03 15:39:09

标签: javascript jquery html

我想在我控制范围之外的几百个网页中移动表格的列,以使其打印精美。我可以使用XPATH轻松地访问有问题的表,但是重新安排它们使我感到困惑。本质上,我想重新排列:

表格:

Header1 Header2
data1   data2

对此:

表1:

Header1
data1

表2:

Header2
data2

这可能吗?

或者,是现有HTML的简化视图:

<table><tbody>
<tr>
<th>Header1</th>
<th>Header2</th>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
</tr>
</tbody></table>

不一定要使它们成为单独的表,但是data部分的宽度足以容纳一个页面,因此它们不能在同一行中。

谢谢!

更新:

我一直在学习jQuery,看起来我可以使用这样的东西:

function jqsplit($table, chunkSize) {
  var cols = $("th", $table).length;
  var n = cols / chunkSize;

  for (var i = 0; i <= n; i++) {
     $("<br/>").appendTo("body");
     var $newTable = $table.clone().appendTo("body");
     for (var j = cols; j > 0; j--) {
         if (j + chunkSize - 1 <= chunkSize * i || j > chunkSize * i + 1) {
             $('td:nth-child(' + j + '),th:nth-child(' + j + ')', $newTable).remove();
         }
     }
  }  
}

(从here处盗用,但针对我的特定用例进行了修改。)

我现在遇到的问题是我无法弄清楚如何使用jquery选择初始表,以及是否可以一起处理它们。原始表始终具有2行和3列,并且没有其他表符合该条件,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

好的,解决了。我的解决方案虽然非常糟糕,但效果很好。糟糕的代码,走了!

function jqsplit($table, chunkSize) {
    //Splits these specific tables into 3 by creating 3 copies and deleting the unneeded rows.
    var $randomP = $("<p></p>").insertAfter($table);
    var $newTable1 = $table.clone().appendTo($randomP);
    var $newTable2 = $table.clone().appendTo($randomP);
    var $newTable3 = $table.clone().appendTo($randomP);
    $newTable1.children("tbody").children("tr").children("th").get(2).remove();
    $newTable1.children("tbody").children("tr").children("td").get(2).remove();
    $newTable1.children("tbody").children("tr").children("th").get(1).remove();
    $newTable1.children("tbody").children("tr").children("td").get(1).remove();
    $newTable2.children("tbody").children("tr").children("th").get(2).remove();
    $newTable2.children("tbody").children("tr").children("td").get(2).remove();
    $newTable2.children("tbody").children("tr").children("th").get(0).remove();
    $newTable2.children("tbody").children("tr").children("td").get(0).remove();
    $newTable3.children("tbody").children("tr").children("th").get(1).remove();
    $newTable3.children("tbody").children("tr").children("td").get(1).remove();
    $newTable3.children("tbody").children("tr").children("th").get(0).remove();
    $newTable3.children("tbody").children("tr").children("td").get(0).remove();
    $table.remove();
}

//Split table
var tablelist = $("table");
$.each(tablelist, function(index,value){
    if ( $(this).children("tbody").children("tr").children("th").length == 3 && $(this).children("tbody").children("tr").length == 2 && $(this).children("tbody").children("tr").children("td").length == 3) {
        jqsplit($(this), 1);
        //Don't want to do the below because some pages have several matching tables
        //return false;
    }
});