将 JSON 值加载到 dataTables 文本区域字段中

Load JSON value into a dataTables textarea field

每次页面加载时,我都会动态创建一个文本区域,如下所示。

"aoColumnDefs": [
            {
                "aTargets": [4],
                "createdCell": function (td, cellData, rowData, row, col) {
                    $(td).html('<textarea name="playerProfile" class="playerIfo" spellcheck="true" rows="2" cols="60"> </textarea>  ');

                }
            }

我有一个 JSON 正在读取,然后将其存储到一个数组中。我还有一个名为 userProfile 的全局变量,并为其分配 JSON 字段的值。在将文本字段推入我的数组后,我尝试了各种方法来动态加载文本字段中的字段,但这似乎不起作用。我可以看到每个 userProfile 的状态,但是我似乎无法进入文本区域。我在控制台中没有看到任何空值或错误,所以我得出结论,我加载到文本区域的方式不正确。下面的代码。

function getPlayerData() {
    $.ajax({
        url: urlToUse,
        dataType: 'json',
        type: 'GET',
    }).done(function (response) {
        renderTeamPlayerData(response);
    });
}
    function renderTeamPlayerData(result){ 
          var DataArray = [];
          var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
          ];
         $.each(result.players, function () {
            userProfile = this.userProfile;
            console.log("starting player profile -> " + userProfile );
            var rawDate = new Date(this.contractUntil);
            var datePretty = monthNames[rawDate.getMonth()] + ", " + (rawDate.getDate()) 
            + " " + rawDate.getFullYear();
            DataArray.push([this.name,
                            this.nationality,
                            this.position,
                            userProfile,
                            datePretty
            ]);
            console.log("player profile -> " + userProfile );
            $(this).closest('tr').find('.playerIfo').text(userProfile );
            //$(this).closest('tr').find('.playerIfo').val(userProfile );
            console.log("player profile after -> " + userProfile );
            //$(this).closest('table tr>td').find('textarea').val(userProfile);
            //$(".playerIfo").text(userProfile);
            //$('textarea[name=playerProfile]').innerHTML =userProfile ;
        });
        $('#playerTable').dataTable().fnAddData(DataArray);
        $('#playerTable').dataTable().fnAdjustColumnSizing();
    }

有人可以告诉我动态加载 JSON 字段(我存储在数组中)的方法吗?

你在倒退。您试图在创建 table 元素之前插入 userProfile,即在 fnAddData(DataArray) 之前。

由于 userProfile 存在于数据中,因此无需通过代码注入。删除 $(this).closest('tr').find('.playerIfo').text(userProfile ); 并使用 render() 回调而不是 createdCell() :

"aoColumnDefs": [{
   "aTargets": [4],
   "render": function(data, type, full, meta) {
     if (type == 'display') {
       return '<textarea name="playerProfile" class="playerIfo" spellcheck="true" rows="2" cols="60">'
            + data 
            + '</textarea>';
     }
     return data
   } 
}]