在DataTables 1.10中,在行添加时放置数据属性

8

我使用以下代码在DataTables 1.10.2中使用table.row.add()方法动态添加新行:

table.row.add([
    '',
    name,
    target_l,
    details,
    panel.html()    
]).draw();

我制作了这个标记:
<tr role="row" class="odd">
    <th>1 .</th>
    <td class="sorting_1">ID Fee</td>
    <td>All students</td>
    <td></td>
    <td>
        <button class="btn btn-null btn-xs" onclick="_remove(59, 'ID Fee')">
            <span class="fui-cross"></span>
        </button>
        <button class="btn btn-null btn-xs" onclick="_edit(59, 'ID Fee', '', '')">
            <span class="icon-pencil"></span>
        </button>
    </td>
</tr>

我想要做的是,在插入新行之后,将data-id属性(和其他数据)添加到新添加的tr标签中,使其类似于以下内容:

<tr data-id="59" role="row" class="odd">

使用以下代码,我已成功获取了新添加行的索引,并且它返回最后一行的索引

var i = table.row.add([
    '',
    name,
    target_l,
    details,
    panel.html()    
]).index();

同时尝试使用该索引进行以下操作,以添加data-id属性

var id = $("#department_id").val();
table.row(i).attr("data-id", id);
// table.row(i).data("id", id);
// I wanted to try this but there is also a method called data() already in
// DataTables so it will not work like in JQuery.

我初次接触DataTables并已经浏览了它的源代码和注释。虽然我不太懂以_fn*()开头的函数,但如果有其他不依赖于这些_fn*()函数的方法,请告诉我,谢谢!


在你的注释代码中,你说你想做类似于 table.row(i).data("id",id); 的操作,但是由于 DataTables 有一个名为 data 的函数,所以无法这样做。你尝试过将 table.row(i) 包装在 jQuery 函数中,然后调用 jQuery 的 data 吗? - Blundering Philosopher
2
table.row(i) 不是一个 jQuery 对象。你不能期望数据或属性函数能够与它一起工作。你需要先将它包装在 jQuery 函数中,然后才能使用其他函数 $(table.row(i)).data("id", id); - evolutionxbox
你解决过这个问题吗,还是它仍然是一个未解决的问题? - davidkonrad
我还没有解决这个问题。 :-( - Gideon
1个回答

12

您可以使用rows().nodes() API函数,如下所示:

var i = table.row.add([
    '',
    name,
    target_l,
    details,
    panel.html()    
]).index();

var id = $("#department_id").val();
table.rows(i).nodes().to$().attr("data-id", id);

不确定为什么,但是 .to$() 在我的 .node() 上无法工作。我不得不使用 $( table.row(i).node() ) - Felipe Leão
1
@FelipeLeão,感谢您的评论。看起来 to$() 只适用于 nodes() 而不是 node(),这有点没有记录。您的解决方法很好。 - Gyrocode.com
2
.to$()将节点转换为jQuery元素。 - mpemburn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接