jquery-datatables-rails gem 不适用于 table

jquery-datatables-rails gem not applying to table

我正在使用 rails 4.2.4,在生成基本产品脚手架后,我似乎无法获得 gem jquery-datatables-rails。我正在使用 github 自述文件和 railscast 插曲来尝试让它正常工作,但运气不佳。

http://railscasts.com/episodes/340-datatables

https://github.com/rweng/jquery-datatables-rails

宝石文件

gem 'jquery-datatables-rails', '~> 3.3.0'

application.js

//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require turbolinks
//= require_tree .

jQuery -> $('.datatable').DataTable();

application.css

*= require dataTables/jquery.dataTables
*= require_tree .
*= require_self

index.html.erb

<table class="datatable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>      
    </tr>
  </thead>

  <tbody>
    <% @products.each do |product| %>
      <tr>
        <td><%= product.name %></td>
        <td><%= product.price %></td>
      </tr>
    <% end %>
  </tbody>
</table>

我尝试在我的 gem 文件中直接引用 github 存储库。生成安装似乎没有以任何一种方式正确添加要求,所以我手动将它们放入。

通过将此脚本放入视图设法解决此问题

<script>
  $(document).ready(function() {
    $('.datatable').dataTable();
  } );
</script>

对于未来的读者,您可以这样做而不是上面接受的答案。您可以将其直接转储到您的 appliation.js 文件中 - 我不喜欢将脚本放在您的视图中的想法,正如上面的答案所建议的那样:

添加到Application.js

$(document).ready(function(){
  $("table[role='datatable']").each(function(){
    $(this).DataTable({
      processing: true      
    });
  });  
})
  • 仅在文档准备好后加载。​​
  • 作用于角色元素,而不是 id - 当您希望对几个 table 应用相同的逻辑时,这会变得很麻烦。

别忘了添加角色='datatable' 到您的 html table.

  • 将角色='datatable'添加到您的table。
  • 确保你有一个 theader 元素和一个
  • tbody 元素