【问题标题】:Assign different attribute to each column in datatables为数据表中的每一列分配不同的属性
【发布时间】:2016-04-19 16:47:37
【问题描述】:

我的数据表已成功完成

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

我在数组中有属性如图:

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

其中1718fieldonefieldtwo 的ID。

数据表代码

 $('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,因为它会为所有&lt;td&gt; 元素分配相同的属性。是否有任何参数来分配不同的属性?

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

或者有什么方法可以从回调函数中分配属性?这样我就可以在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');
   });
}

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

【问题讨论】:

  • 你显示的attributes 是一个PHP var_dump。 attributes 客户端在哪里?它看起来怎样?它来自哪里,如何传递给客户端?
  • attributes 在回调函数本身计算。如果我可以将其设置为通知 DT 将其分配为属性?但现在 AFAIK,这是不可能的 :(
  • 您正在使用$.each(attributes,... - 什么是attributes - 它包含什么?它来自哪里?
  • 这个 js 写在 tpl 文件中,我从 php 将属性分配为 $attributes 数组的 json_encode。
  • 那么为什么不显示attributes js,现在它对于解决方案至关重要?那么或许我们可以看出1718的含义为id的...

标签: javascript php jquery datatables


【解决方案1】:

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

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

//$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;
},

【讨论】:

    猜你喜欢
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2016-09-19
    • 2017-07-10
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多