【问题标题】:jQuery datatable if data length greater than certain length如果数据长度大于某个长度,则 jQuery 数据表
【发布时间】:2017-08-11 20:14:16
【问题描述】:

我曾经使用 PHP 来打印我的数据表。当我到达一个字符串大于 17 个字符的特定列时,我将使用以下内容在第 17 个字符之后打印省略号:

if(strlen($row[tli]) > 17){echo "<td><a href='#'>".substr(row['number'],0,17)."..."</a></td>";}

我需要使用 ajax 来做同样的事情。

$('#example1').DataTable({      
  "ajax": {
    "url": "api/displayQnams.php",
    "type": "POST",
    "dataSrc": ''
  },
  "columns": [
    {
      "data": "number",
      "fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
      {
        if(oData.number.length > 17) // here is where the initial check starts
        {$(nTd).html("<a href='#'>'"+oData.number+"...'</a>")} // here is where it should print the ellipses after the 17th character
        else
        {$(nTd).html("<a href='#'>'"+oData.number+"'</a>"}
      }
    }
  ]
});

oData.number.length 在控制台中给我以下错误:

Cannot read property 'length' of undefined

我缺少什么来完成这项工作?

【问题讨论】:

    标签: javascript jquery json ajax datatables


    【解决方案1】:

    问题是某些 oData 为空,您无法使用长度比较空值。所以我创建了一个变量,如果 oData.number 为 null,则将变量设置为 ''。

    这是我如何让它工作的:

    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
    {
      if(oData.tli == null || oData.tli == ""){var tlinumber = '';}
      else{var tlinumber = oData.tli;}
      if(tlinumber.length > 17)
      {
        $(nTd).html("<a href='#'>'"+tlinumber.substring(0, 17)+"...'</a>")
      }
      else
      {
        $(nTd).html("<a href='#'>'"+tlinumber+"'</a>"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 2019-04-13
      • 1970-01-01
      相关资源
      最近更新 更多