简体   繁体   English

根据 AJAX 响应动态添加 id 到数据表行

[英]Dynamically add id to datatable row based on AJAX response

I have seen posts on giving arbituary ids to datatable rows using row callback here .我看到的让arbituary ID来使用行回调的数据表行的帖子在这里 I want to give rows specific ids based on my AJAX response dataToUse ;我想根据我的 AJAX 响应dataToUse给行特定的 id; each row will have a unique id given as one field of a JSON object.每一行都有一个唯一的 id,作为 JSON 对象的一个​​字段。 Here's the structure of my datatable:这是我的数据表的结构:

table = $('#_table').dataTable({
                ajax: function (data, callback, settings) {
                    $.ajax({
                             type: "post",
                             url: '/test/getvalues',
                             dataType: "json",
                             success: function (result) {
                                var dataToUse = {};
                                dataToUse.data = result.map.count;
                                callback(dataToUse);
                             }
                           });
                  }
        })

}

Do you just want to perform some operation on particular rows based on the information you get from dataToUse?您是否只想根据从 dataToUse 获得的信息对特定行执行某些操作? To begin, I'll describe the behavior that is happening in the example you provide.首先,我将描述您提供的示例中发生的行为。 The code reads:代码如下:

if ( data[5].replace(/[\$,]/g, '') * 1 > 150000 ) {
    $('td', row).eq(5).addClass('highlight');
}

Which is checking to see if the 6th item in data, the salary, is greater than 150,000, and if it is, selecting that item using a CSS selector through jQuery and then is adding a class to it.这是检查数据中的第 6 项,即薪水,是否大于 150,000,如果是,则通过 jQuery 使用 CSS 选择器选择该项目,然后为其添加一个类。

Based on your question, you want to perform a similar table-modifying behavior based on some data provided by result to dataToUse.根据您的问题,您希望根据 result 提供给 dataToUse 的一些数据执行类似的表修改行为。 In that case, result will need to provide some sort of information that allows you to construct an appropriate jQuery selector, $(someSelector) to choose the rows you want to modify, and then you can modify them as needed.在这种情况下, result 将需要提供某种信息以允许您构建适当的 jQuery 选择器, $(someSelector) 来选择要修改的行,然后您可以根据需要修改它们。 You can perform all this in your success function.您可以在您的成功功能中执行所有这些操作。

I would suggest updating their classes rather than ids if you want to add some specific styling or behavior to them.如果您想向它们添加一些特定的样式或行为,我建议更新它们的类而不是 id。 Updating the id tends to be bad practice.更新 id 往往是不好的做法。

this post , whose answer has been pasted here, gives the answer,这篇文章,其答案已粘贴在这里,给出了答案,

    'fnCreatedRow': function (nRow, aData, iDataIndex) {
        $(nRow).attr('id', 'my' + iDataIndex); // or whatever you choose to set as the id
    },

aData somehow is the AJAX data that I received. aData不知何故是我收到的 AJAX 数据。 This is like magic to me but it worked!这对我来说就像魔术,但它奏效了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM