Datatables.js - 来自 URL JSON 数据的超链接

Datatables.js - hyperlink from URL JSON data

我有一些 JSON 示例数据,其中有一个 URL 对象。当我将数据添加到数据表中时,我得到的是 URL 作为文本,而不是 link.

var items = [    
    {
    "Alert": "Alpha",
    "Date": "23/04/2021",
    "Information": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In a ultrices nisl, ac interdum libero. Vestibulum ac convallis mauris, auctor hendrerit augue. Vivamus elementum sapien eget dui maximus, quis laoreet magna pulvinar. Sed feugiat hendrerit est, et tincidunt lorem pellentesque nec. Quisque consequat laoreet eros in porta.",
    "Name": "Tester",
    "Status": "Live",
    "URL": "https://www.google.com/",
    "Updated": "21/04/2021 09:35"
}
]

数据表:

$(document).ready(function () {
 var items = JSON.parse(request.responseText);
$('#thisTable').dataTable({
    "aaData": items,
    columns: [
        { title: "Date", "mDataProp": "Date" },
        { title: "Status", "mDataProp": "Status" },
        { title: "Alert", "mDataProp": "Alert" }, 
        { title: "Updated", "mDataProp": "Updated"},
        { title: "Name", "mDataProp": "Name" },
        { title: "Information", "mDataProp": "Information" },
        { title: "URL", "mDataProp": "URL"}      
    ],     
}); 
});

我已经通读了文档,其中提到分配一个函数来获取 URL,但是当我包含以下内容时,我只是收到控制台错误。第一次尝试使用带有 JSON 源的数据表,这有点复杂。

"data": "URL",
    "render": function ( data, type, row, meta ) {
      return '<a href=" + URL +">LINK</a>';
    }

这里有几个问题:

  1. 构建您的 link HTML 的代码需要更改。现在,您只是构建一个由 ':
  2. 包围的字符串
return '<a href=" + URL +">LINK</a>';

因此,该字符串中的变量名不被视为变量。只是按字面理解为一段文字而已。

改为使用:

return '<a href="' + data + '">LINK</a>';

(使用 data 而不是 URL 的解释如下)。

  1. 您可以将列渲染器组合到 URL 列定义中。您可以使用渲染函数的 data 变量(见下文)。

有第三个(可选)更新 - 将旧变量名称(例如 aaData)替换为新版本(data)。您可以看到这些新旧名称的列表 here.

结合以上所有点得出:

$('#thisTable').dataTable({
    "data": items,
    columns: [
        { title: "Date", data: "Date" },
        { title: "Status", data: "Status" },
        { title: "Alert", data: "Alert" }, 
        { title: "Updated", data: "Updated"},
        { title: "Name", data: "Name" },
        { title: "Information", data: "Information" },
        { 
          title: "URL", 
          data: "URL",
          render: function ( data, type, row, meta ) {
            return '<a href="' + data + '">LINK</a>';
          }
        }      
    ]
});

在 URL 列中,我使用 data: "URL" 将 URL 值分配给名为 data 的变量,然后 DataTables 在渲染函数中使用该变量。