首页 > 解决方案 > jQuery Datatables:使用外部按钮复制到剪贴板

问题描述

我想使用数据表中不包含的按钮将数据表内容复制到剪贴板。

buttons: ['copyHtml5']使用该选项可以很容易地使用 Datatables 中的按钮执行此操作。

是否可以链接 html 按钮的 onclick() 方法来执行此操作?

例如,我对搜索过滤器做了同样的事情,这段代码将外部 html 输入 (myFilter) 与 Datatables 搜索操作链接起来:

$("#myFilter").on("keyup", function() {
    dataTable.search(this.value).draw();
}); 

标签: datatables

解决方案


你可以做这样的事情来触发复制。

var table=  $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [           
          
            'copy'
       
             
        ]
    } );
    
    $("#copycustomButton").on("click", function() {
    table.button( '.buttons-copy' ).trigger();
});
.buttons-copy{
  display:none !important
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.0.min.js"></script>
      <script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
      <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.1.2/js/dataTables.buttons.min.js"></script>
   
      <script type="text/javascript" src="//cdn.datatables.net/buttons/1.1.2/js/buttons.html5.min.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
      <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.1.2/css/buttons.dataTables.min.css">
    
<button id="copycustomButton">
copy
</button>
<table id="example" class="display" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>

    </tr>
    <tr>
      <td>Garrett Winters</td>
      <td>Accountant</td>
      <td>Tokyo</td>

    </tr>
    <tr>
      <td>Ashton Cox</td>
      <td>Junior Technical Author</td>
      <td>San Francisco</td>

    </tr>
    <tr>
      <td>Cedric Kelly</td>
      <td>Senior Javascript Developer</td>
      <td>Edinburgh</td>

    </tr>
    <tr>
      <td>Airi Satou</td>
      <td>Accountant</td>
      <td>Tokyo</td>
    </tr>
    <tr>
      <td>Brielle Williamson</td>
      <td>Integration Specialist</td>
      <td>New York</td>
    </tr>
    <tr>
      <td>Herrod Chandler</td>
      <td>Sales Assistant</td>
      <td>San Francisco</td>
    </tr>
    <tr>
      <td>Rhona Davidson</td>
      <td>Integration Specialist</td>
      <td>Tokyo</td>
    </tr>
    <tr>
      <td>Colleen Hurst</td>
      <td>Javascript Developer</td>
      <td>San Francisco</td>
    </tr>

    <tr>
      <td>Jennifer Chang</td>
      <td>Regional Director</td>
      <td>Singapore</td>
    </tr>
    <tr>
      <td>Donna Snider</td>
      <td>Customer Support</td>
      <td>New York</td>
    </tr>
  </tbody>
</table>


推荐阅读