微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用动态数据表用字符串替换行值 - javascript

如何解决如何使用动态数据表用字符串替换行值 - javascript

我正在使用数据表来获取电子邮件的状态

例如,0 表示未订阅,1 表示订阅

我想将“0”和“1”替换为“unsubscribed”和“subscribed

在我的 HTML 中有这个

<table class="table table-striped table-bordered table-hover"
       id="mail-recipient-table">
  <thead>
  <tr>
    <th>{{__('digestReport.columns.item')}}</th>
    <th>{{__('digestReport.general.name')}}</th>
    <th>{{__('digestReport.general.email')}}</th>
    <th>{{__('digestReport.table.columns.email_state')}}</th>
  </tr>
</table>

在我的 javascript 中,我有这个:

$(document).ready(function () {
  let dataTable;
  let itemCounter = 1;
  axios.get('{{route('digest-report.mail-recipients',$digestReport->id)}}')
.then((response)=>{
    dataTable= $('#mail-recipient-table').DataTable({
      "processing": true,"autoWidth": false,"responsive": true,"dom": '<t>ip',"order": [0,'asc'],"language": {
        "url": '{{session('locale') == 'en' ? "//cdn.datatables.net/plug-ins/1.10.20/i18n/English.json" : "//cdn.datatables.net/plug-ins/1.10.20/i18n/Japanese.json"}}',"buttons": {
          "reload": '{{__('tableButtons.reload')}}'
        }
      },});
    $.each(response.data,function (i,e){
      addRow(itemCounter,e.name,e.email,e.state);
      itemCounter++;
    });
  });

  function addRow(itemCounter,name,email,state){
    dataTable.row.add([
      itemCounter,state
    ]);
  }
})

我的数据表工作正常,但我的状态列显示 0 和 1

如何更换?

enter image description here

解决方法

您需要在表定义中设置渲染方法:

$myTable = $('#myTable').DataTable({
    columnDefs: [
        {targets: 3,render:subRender}
    ]
});


function subRender(data,type){
    if (type === 'display'){
        if (data == "0") return "Unsubscribed";
        if (data == "1") return "Subscribed";
        return data;
    }
    return data;
}

这允许您以任何方式显示数据(甚至返回 html),而不会影响用于排序或其他计算的基础数据。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。