将Datatables与.json源文件一起使用,我试图在数据显示在表中之前对其进行操作。在此示例中,我试图简单地删除空格并用破折号代替。

我了解有两种方法可以进行一些数据操作。一个是columnDefs,另一个是使用dataSrc并返回数据。当我尝试使用.split或.replace甚至.toLowerCase()时,两者均会失败。

例如,我添加了columnDefs,如下所示:

 columnDefs: [
            {
                "render": function ( data, type, row ) {
                  console.log(data);
                  var cn = data.split(" ").join("-").toLowerCase();
                  return cn;
                },
                "targets": 1
            }
        ],


控制台显示:

Uncaught TypeError: data.split is not a function


我们如何用replace或类似方法操纵数据?

我的数据如下:

{
    "Licensee": "Whistles for Woods",
    "Contact Name": "Bob",
    "Street": "2230 Trail",
    "Suite / PO Box": 0,
    "City": "Alturas",
    "ST": "CA",
    "Zip Code": 997733,
    "Telephone": 0,
    "Email Address": "bobc@email.com",
    "Website Address": "www.domain.com",
    "Fax": "No fax",
    "Products": "whistle with custom logo",
    "Categories": "Miscellaneous"
  },

最佳答案

如评论中所述

我们只想确保我们确实在操纵字符串,而不是其他任何数据类型。因此,在这种情况下,我们将代码更改为如下所示:

 columnDefs: [
        {
            "render": function ( data, type, row ) {
              if(typeof data === 'string'){
                  //only if string manipulate
                  data = data.split(" ").join("-").toLowerCase();
              }
              // OR data = data.toString(); whichever is more convenient!
              return data;
            },
            "targets": 1
        }
    ],

09-25 16:58
查看更多