如何使用 js 将数据链接动态添加到数据表行

How to add data-link dynamically to datatables row with js

本文关键字:添加 数据表 动态 链接 何使用 js 数据      更新时间:2023-09-26

>我有带有可点击行的表格,它渲染控制器显示操作,为了向数据库添加新记录,有一个按钮可以呈现新操作并在不刷新页面的情况下打开一个弹出窗口,在弹出窗口中提交表单后,它会动态地将新行添加到数据表中而不刷新,所有以前的都工作正常,除了新添加的行不可单击之外这是表代码

<%- model_class = Supplier -%>  
<table class="table table-custom pointer" id="editable-usage">
<thead>
<tr>
  <th class="table-text-center"><%= model_class.human_attribute_name(:name) %></th>
  <th class="table-text-center"><%= model_class.human_attribute_name(:code) %></th>
  <th class="table-text-center"><%= model_class.human_attribute_name(:email) %></th>
  <th class="table-text-center"><%= model_class.human_attribute_name(:total_credit) %></th>
  <th class="table-text-center"><%= model_class.human_attribute_name(:notes) %></th>
</tr>
</thead>
<tbody>
 <% @suppliers.each do |supplier| %>
  <tr data-link="<%= supplier_path(supplier) %>">
    <td><%= supplier.name %></td>
    <td><%= supplier.id %></td>
    <td><%= supplier.email %></td>
    <td><%= supplier.total_credit %></td>
    <td><%= supplier.notes %></td>
  </tr>
<% end %>
</tbody>
</table>

创建.js.erb文件代码:

// hide the popup
$('#splash').modal('hide');
// insert the new row
 var t = $('#editable-usage').DataTable();
 t.row.add([ '<%= @supplier.name  %>','SC00<%=@supplier.id %>','<%=@supplier.email %>','','<%=@supplier.notes %>']).draw();

如何将 ( 数据链接="<%= supplier_path(供应商) %>" ) 添加到这个新的 TR

你不能做像$(tr).data("link", "<%= supplier_path(supplier) %>");这样的事情吗.

也许这不是最优雅的解决方案,但你可以把回调放在表重绘事件上,像这样

t.on( 'draw', function () {
    $(t+'>tr').attr(data-link="<%= supplier_path(supplier) %>");
} );

我认为如果没有回调就不会添加它。

我找到了参考@datatables解决方案

我添加到创建.js.erb

t.row.add([ '<%= @supplier.name  %>','SC00<%=@supplier.id %>','<%=@supplier.email %>','','<%=@supplier.notes %>']).draw().nodes().to$().attr("data-link", "<%= supplier_path(@supplier) %>");

并添加到 js 文件中

var oTable = $('#editable-usage').DataTable();
oTable.on( 'draw', function () {
    $("tr[data-link]").click(function () {
        window.location = this.dataset.link
    });
}); 

似乎我应该添加 .nodes() .to$() 以便我可以添加属性