为数据表中的每列指定不同的属性

时间:2016-01-14 11:17:52

标签: javascript php jquery datatables

我已成功完成dataTable

我所要做的就是将属性分配给此表的列。

我在数组中有如下所示的属性:

$attributes = array('7' => array(
  '17' => array(
    'class' => 'editable'
  )
  '18' => array(
    'class' => 'custom_7_18 editable'
  )
)

enter image description here

其中1718fieldonefieldtwo的ID。

dataTable的代码

 $('table.crm-multifield-selector').dataTable({
  "bProcessing": true,
  "asStripClasses" : [ "odd-row", "even-row" ],
  "sPaginationType": "full_numbers",
  "sDom"       : '<"crm-datatable-pager-top"lfp>rt<"crm-datatable-pager-bottom"ip>',
  "bServerSide": true,
  "bSort" : false,
  "sAjaxSource": sourceUrl,
});

我无法在数据表中使用sClass,因为它会为所有<td>元素分配相同的属性。是否有任何param分配不同的属性?

我可以将$attribute数组中的属性分配给dataTable吗?

或者有没有办法从回调函数中分配属性?这样我就可以在php文件中使用这个$attribute数组,并且dataTable每次绘制一行时都会分配这个属性吗?

我试过这个 -

"fnCreatedRow": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
   $.each(attributes, function(index, item) {
     //as the number of column can be changed, I can't give 
     //hardcoded values as I found during searching like 
      $('td:eq(2)', nRow).addClass('editable');
   });
}

有没有人遇到过这样的情况?

1 个答案:

答案 0 :(得分:0)

我刚刚解决了这个问题,想在这里分享:) -

为回调函数本身中的每个单元格分配属性,即将单元格值更改为包含数据的数组以及属性(例如:class)

//$value is the array sent to dataTable
foreach ($value as $fieldId => &$fieldName) {
  if (!empty($attributes[$fieldId][$id]['class'])) {
    //change the fieldName to array containing the attributes and the data part
    $fieldName = array(
      'data' => $fieldName, 
      // as I said in the question, I had $attributes array for the fields ids
      'fieldClass' => $attributes[$fieldId][$id]['class']
    );
  }
}

调整此项以使用标准fnRowCallback复制dataTable:

//Add class attributes to cells
"fnRowCallback": function(nRow, aData) {
   // iterate through each row
   $('td', nRow).each(function(index, element) {
     if (typeof aData[index]=='object') {
       if (typeof aData[index].fieldClass != 'undefined') {
         $(element).addClass(aData[index].fieldClass);
       }

       if (typeof aData[index].data != 'undefined') {
         $(element).html(aData[index].data);
       }
     }
   });
   return nRow;
},
相关问题