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



>假设我有一个看起来像这样的表:

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

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

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

不幸的是,数据表中没有这样的东西。很难看出为什么有人应该为该特定任务制作一个专门的插件。但是,这里有一个小函数可以为您完成这项工作:

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();
});

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

最新更新