Export tablesorter table to CSV and replace content of specific columns

问题: As the title says, I use tablesorter on an HTML table and I would like to add also the functionality of downloading the whole table in a CSV file. My problem is that some...

问题:

As the title says, I use tablesorter on an HTML table and I would like to add also the functionality of downloading the whole table in a CSV file.

My problem is that some of the columns don't include text but either an image or an icon. For example,

<table class="tablesorter">
   <thead>
      <tr>
         <th>Col1</th>
         <th>Col2</th>
         <th><i class="icon-2" role="img" aria-label="ColIcon2" title="ColIcon2"></i></th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>This is just a text</td>
         <td><a href="/blah" class="class1"><img src="/Img/Icons/image.gif" alt="title1" title="title1"></a></td>
         <td><i class="icon-1" role="img" aria-label="Icon1" title="Icon1"></i></td>
      </tr>
   </tbody>
   <tfoot>
      <tr >
         <td>
            <a href="#" class="download">Download as CSV</a>
         </td>
      </tr>
   </tfoot>
</table>

And use the regular, basic setup on tablesorter as this

$(function () {
    var $table = $('table');

    $('.download').click(function() {
        // tell the output widget do it's thing
        $table.trigger('outputTable');
    });

    $table.tablesorter({
        theme: 'blue',
        widgets: ['zebra', 'output'],
        widgetOptions: {
             output_includeFooter: false
        },
    });
});

I am clueless how I could make it that on the positions where there is an Icon or Image, I could either add the title attribute or a custom data-attribute I will add on the HTML code?


回答1:

Within the widgetOptions add a output_formatContent callback that returns the text that is to be included in the CSV:

output_formatContent : function( c, wo, data ) {
  // data.isHeader (boolean) = true if processing a header cell
  // data.$cell = jQuery object of the cell currently being processed
  // data.content = processed cell content (spaces trimmed, quotes added/replaced, etc)
  // data.columnIndex = column in which the cell is contained (added v2.30.5)
  // data.parsed = cell content parsed by the associated column parser (added v2.30.5)
  // **********
  // use data.$cell.html() to get the original cell content
  const label = data.$cell.find('img, i');
  return label.length ? label.attr('title') : data.content;
}
  • 发表于 2018-12-25 15:46
  • 阅读 ( 422 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除