动态添加行时不应用数据属性 [英] Data attributes are not applied when I add a row dynamically
问题描述
当我通过 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();
} );
但是如果我再搜索Tiger"什么都没有出现.
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();
} );
搜索老虎"现在工作
这篇关于动态添加行时不应用数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!