动态添加行时未应用数据属性 [英] Data attributes are not applied when I add a row dynamically

查看:49
本文介绍了动态添加行时未应用数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过JavaScript代码向数据表中添加一行时,则不会应用搜索和排序选项.我修改了数据属性示例:

When I add a row to a Datatable via javascript code then the search and sort options are not being applied. I modified the data-attributes example thus:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>

$(document).ready(function() {
var t = $('#example').DataTable();
t.row.add($('<tr><td data-search="Tiger Nixon">T. Nixon</td><td>System Architect</td><td>Edinburgh</td><td>61</td><td data-order="1303689600">Mon 25th Apr 11</td><td data-order="320800">$320,800/y</td></tr>'));
t.draw();

} );

但是,如果我随后搜索老虎",什么都没发生.

But if I then do a search for "Tiger" nothing comes up.

这是预期的行为吗?如果可以的话,有没有解决的办法?

Is this expected behaviour and if so is there a way around it?

JSFiddle

推荐答案

问题源于以下事实:只有在初始表中存在data- *属性时,才会检测到该属性.因此,作为解决方案,我提出了以下解决方案:

The problem stems from the fact that data-* attributes will only be detected if they are present in the initial table. So as a work around I came up with the following solution:

使用任何必需的data- *属性在初始表中定义一个虚拟行:

Define a dummy row in the initial table with any required data-* attributes:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr style = "display: none;">
            <td data-search="">/td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>            

然后可以在启动时删除该行:

That row can then be deleted on startup:

$(document).ready(function() {
var t = $('#example').DataTable();
t.row(0).remove();
t.row.add($('<tr><td data-search="Tiger Nixon">T. Nixon</td><td>System Architect</td><td>Edinburgh</td><td>61</td><td data-order="1303689600">Mon 25th Apr 11</td><td data-order="320800">$320,800/y</td></tr>'));
t.draw();

});

搜索老虎"现在可以使用

Searching for "Tiger" now works

这篇关于动态添加行时未应用数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆