You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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 createdRow callback 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 row
    • data: The full JSON object for that row (includes your IdNumber field)
    • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:22:39