数据表:合并具有相似数据的行

时间:2014-12-27 09:09:27

标签: html datatables html-table jquery-datatables

假设我有一个如下所示的表:

<table>
 <thead>
  <tr>
   <th>Price</th>
   <th>Product</th>
   <th>Supplier</th>
  </tr>
 </thead>

 <tbody>
  <tr>
   <td>$20</td>
   <td>camera</td>
   <td>Supp1</td>
  </tr>

  <tr>
   <td>$30</td>
   <td>laptop</td>
   <td>Supp1</td>
  </tr>

  <tr>
   <td>$35</td>
   <td>keyboard</td>
   <td>Supp2</td>
  </tr>

  <tr>
   <td>$40</td>
   <td>camera</td>
   <td>Supp2</td>
  </tr>
 </tbody>
</table>

使用Datatables库,是否可以将具有相同产品(相机)的行合并为一行,列出两个供应商的价格?所以结果会是这样的:

<table>
 <thead>
  ...
 </thead>

 <tbody>
  <tr>
   <td>Supp1: $20<br />
       Supp2: $40</td>
   <td>camera</td>
   <td>Supp1 & Supp2</td>
  </tr>

  <tr>
   <td>$30</td>
   <td>laptop</td>
   <td>Supp1</td>
  </tr>

  <tr>
   <td>$35</td>
   <td>keyboard</td>
   <td>Supp2</td>
  </tr>
 </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

不幸的是,在dataTables中没有这样的东西。并且很难理解为什么有人应该为该特定任务制作专门的插件。但是,这是一个为您完成工作的小功能:

function consolidate() {
    var product = '',
        productRows,
        products = [];

    //get a unique list of products    
    $("#example tbody tr td:nth-child(2)").each(function() {
        product = $(this).text();
        if (products.indexOf(product)<0) products.push(product);
    });

    //get all rows with a certain product
    function getProductRows(product) {
        var rows = [];
        $("#example tbody tr").each(function(index, tr) {
            if ($(tr).find('td:eq(1)').text() == product) {
                rows.push(tr);
            }
        });
        return rows;
    };

    //iterate through tbody, assemble duplicated products in a single row
    //remove duplicated rows
    $tbody = $('tbody');
    products.forEach(function(product) {
        productRows = getProductRows(product);
        if (productRows.length > 1) {
            var price,
                supplier,
                prices = '',
                suppliers = '';

            for (var i=0;i<productRows.length;i++) {
                var $row = $(productRows[i]);
                supplier = $row.find('td:eq(2)').text();
                price = $row.find('td:eq(0)').text();
                if (prices !== '') prices+='<br>';
                if (suppliers !== '') suppliers+=' & ';                
                prices+=supplier+': '+price;
                suppliers+=supplier;
                $row.remove();
            }    
            $tbody.append('<tr>'+
                          '<td>'+prices+'</td>'+
                          '<td>'+product+'</td>'+
                          '<td>'+suppliers+'</td>'+
                          '</tr>');
        }            
    });        
}

在初始化数据表之前调用该函数:

consolidate();

$(document).ready(function() {
    var table = $('#example').DataTable();
});

小提琴 - &gt;的 http://jsfiddle.net/ky9hm7c9/
现在,您可以将上述代码包装到dataTables插件中,但我认为这不值得付出努力。