从Json渲染DataTable,并修改其中一列

时间:2016-05-13 13:00:29

标签: javascript jquery html json datatable

我正在从服务器加载的Json-File中呈现DataTable的行。

其中一个列包含徽标(图像)的链接,但该链接不应该作为纯文本呈现,而不是作为徽标直接呈现。

我怎么能这样做?

以下是我呈现DataTable的代码:

$(document).ready(function() {
    $('#osPartner').DataTable( {
        "ajax": "test2.json",
        "columns": [
            { "data": "pId" },
            { "data": "sName" },
            { "data": "lgName" },
            { "data": "logo" },
            { "data": "inc" },
            { "data": "details.teaserImage2" }
        ]
    } );
} ); 

加载了所有数据,但“徽标”列是链接。我如何显示该链接上的图像而不是链接(作为文本)?是否有可能修改该列,并用html代码包围链接,如:

<img src="logo_url_here_that_i_become_from_jsom" alt="Mountain View" style="width:304px">

 logo = "<img src='"+ logo + "' alt='Mountain View' style='width:304px'>"

以下是我的json文件的样子:

{
    "data": [
    {
        "sName": "hjp",
        "lgName": "Hi Ju Pi",
        "pId": "lap34208",
        "feat": false,
        "logo": "https://www.link-here.de/images/image1.png",
        "details": {
              "teaserImage": "https://link-here.de/mg/dsa/dev/img/image1.png",
               "teaserImage2": "https://link-here.de/mg/dsa/dev/img/image1.png"
        }
        },
        {
        "sName": "hjp2",
        "lgName": "Hi Ju Pi22",
        "pId": "ldfsdf38",
        "feat": false,
        "logo": "https://www.link2-here.de/images/image2.png",
        "details": {
              "teaserImage": "https://another-link-here.de/mg/dsa/dev/img/picture1.png",
               "teaserImage2": "https://another-link-here.de/mg/dsa/dev/img/pic2.png"
        }}
    }]

}

1 个答案:

答案 0 :(得分:1)

您可以使用render方法:

"columns": [
   { "data": "pId" },
   { "data": "sName" },
   { "data": "lgName" },
   { "data": "logo",
     render : function( data, type, full, meta ) {
       return type == 'display' ? '<img src="'+ data + '"/>' : data
     }
   },
   { "data": "inc" },
   { "data": "feat" }
]

您可以通过full变量获取该行的所有项目(如果您要为title设置某个<img>或类似内容。)