javascript - 如何在TD标签中添加id?
问题描述
我正在使用 DataTables 插件(我是初学者),我想在<td>
HTML 标记中添加一个“id”。我做了这篇文章中的内容,但这不是我想要的。
我也看到了这篇文章,但我不知道如何使用此代码。
JS:
$('#datatable').dataTable({
"sPaginationType" : "full_numbers",
"createdRow" : function ( row, data_use, dataIndex ) {
$(row).attr('id', dataIndex);
},
data : data_use,
columns : column_name,
dom : 'Bfrtip',
select : 'single',
responsive : true,
altEditor : true,
destroy : true,
searching: true,
buttons : [{
extend : 'selected',
text : 'Edit',
name : 'edit'
}],
});
解决方案
您可以通过columnDefs
在 DataTable 配置中添加一个数组并添加一个createdCell
函数来做到这一点。例如:
$(document).ready(function() {
var table = $('#example').DataTable({
'columnDefs': [{
'targets': "_all", // this will invoke the below function on all cells
'createdCell': function(td, cellData, rowData, row, col) {
// this will give each cell an ID
$(td).attr('id', 'cell-' + cellData);
}
}]
});
运行下面的代码片段以查看完整的示例。您可以右键单击一个单元格(即 a td
)并单击“检查”以查看id
添加到每个单元格的属性。
$(document).ready(function() {
var table = $('#example').DataTable({
'columnDefs': [{
'targets': "_all",
'createdCell': function(td, cellData, rowData, row, col) {
$(td).attr('id', 'cell-' + cellData);
}
}]
});
// Add some data to the table
table.row.add(['Airi Satou', 'Accountant', 'Tokyo', '5407', '2008/11/28', '$162,700']).draw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>
<link href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css" rel="stylesheet" />
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
推荐阅读
- angular - 无法加载翻译和所有后备语言,您是否拼错了范围名称?
- flutter - 在flutter应用程序中从显示带有加载小部件的黑屏调用时如何停止setState?
- postgresql - 如何使用标签标记变更集或变更日志文件 - webdevops/liquibase
- grails - 找不到构造函数“java.lang.String”的参数 0
- java - 如何确保 Java 线程永远不会运行无限循环?
- java - 如何在java中按右移?
- python - 为什么使用 while 循环可以使程序工作,但我原来的 for 循环不起作用?(DNA pset6)
- javascript - 查找最后一次说出一个词
- android - 无法解决 response.body().string() 的问题
- jupyter-notebook - Jupyter 中单元格之间的乳胶方程数重置为 1