如何通过jQuery Ajax服务端为动态表格行添加ID及data-id属性
Add
id and data-id to Dynamically Loaded Table Rows via DataTables Got it! Given your ajax and columns setup, it’s clear you’re using DataTables (the popular jQuery table plugin). Here’s the straightforward solution to add your desired attributes to each generated <tr>:
Modified Full Configuration
// Replace #your-table-id with the actual ID of your table element $("#your-table-id").DataTable({ "ajax": { "url": '/Siparis/SiparisleriDoldur/', "type": 'POST', "dataType": 'json', "data": { liste } }, "columns": [ { "data": "MusteriAdi", "name": "Müşteri Adı" }, { "data": "MalzemeAdi", "name": "Ürün Adı" }, { "data": "SiparisAdet", "name": "Sipariş Adedi" }, ], // This callback handles row customization "createdRow": function(row, data, dataIndex) { // Grab the IdNumber from the row's JSON data const rowId = data.IdNumber; // Set both attributes on the <tr> element $(row).attr({ "id": rowId, "data-id": rowId }); } });
What This Does
- The
createdRowcallback triggers right after a row is created but before it’s added to the DOM—perfect for modifying row attributes without extra DOM manipulation later. - It takes three parameters:
row: The raw DOM<tr>element for the new rowdata: The full JSON object for that row (includes yourIdNumberfield)dataIndex: The position of the row in your dataset (we don’t need it here, but it’s available if you need row-specific logic)
- Using jQuery’s
attr()method lets us set both attributes in a single clean call, pulling the value directly from your returned JSON data.
Example Output
Once implemented, your rows will match exactly what you’re expecting:
<tr id='12345' data-id='12345'> <td>Acme Corp</td> <td>Aluminum Sheet</td> <td>20</td> </tr>
内容的提问来源于stack exchange,提问作者Enes KAYGUSUZ
相关产品推荐
相关产品推荐

