2016-12-06 62 views
1

我有一个textarea动态创建每次页面加载如下。加载JSON值到dataTables textarea字段

"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的状态,但是我似乎无法进入textarea。在控制台中没有看到任何空值或错误,所以我总结说我的加载到textarea的方式是不正确的。下面的代码。

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场(我已经存储在一个数组)?

回答

1

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

由于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 
    } 
}] 
+0

这完美地工作,@davidkonrad –