【发布时间】:2018-07-23 08:18:24
【问题描述】:
我想在使用数据表显示之前从后端自定义 JSON 数据。首先,我想用下划线符号 (_) 替换列 artist.name 中的空格 ()。然后,我想将该列中的每一行与我的代码之类的 wiki 链接进行超链接。
HTML:
<table id="albums" class="table table-striped table-bordered" style="width:100%" >
<thead>
<tr>
<th>Rank</th>
<th>Artist</th>
<th>Album name</th>
<th>Year</th>
<th>Genres</th>
</tr>
</thead>
</table>
数据表-JS:
"columns": [
{"data": "rank", "searchable": false},
{
"data": "artist.name".replace(/\s+/g, '_'), // ex: 'The Beatles' => 'The_Beatles'
"name": "artist.name".replace(/\s+/g, '_'),
"render": function (data, name) {
data = '<a href= "https://en.wikipedia.org/wiki/' + name + '">' + name + '</a>'; // render to: https://en.wikipedia.org/wiki/The_Beatles
return data;
}
},
{"data": "name"},
{"data": "year"},
{"data": "genres", "name": "genres.name", "sortable": false},
]
JSON 数据:
{
"data": [
{
"DT_RowId": "row_1",
"DT_RowAttr": {
"data-pk": 1
},
"rank": 1,
"name": "Sgt. Pepper's Lonely Hearts Club Band",
"year": 1967,
"artist_name": "The Beatles",
"genres": "Psychedelic Rock, Rock & Roll",
"artist": {
"id": 2,
"name": "The Beatles"
}
},
{
"DT_RowId": "row_2",
"DT_RowAttr": {
"data-pk": 2
},
"rank": 2,
"name": "Pet Sounds",
"year": 1966,
"artist_name": "The Beach Boys",
"genres": "Pop Rock, Psychedelic Rock",
"artist": {
"id": 3,
"name": "The Beach Boys"
}
}
...
],
"recordsFiltered": 15,
"recordsTotal": 15,
"draw": 1
}
它不起作用。谁能帮我?谢谢。
【问题讨论】:
-
你能显示你的json数据吗?
-
我已经添加了。
-
这没有意义。为什么要将
data属性更改为不存在的属性? JSON 中没有The_Beatles属性。结果将是一个错误。即使有一个The_Beatles索引,它也不会加起来,因为您实际上会尝试根据行数据多次更改列的name或title。 列只能有一个标题和一个名称。 -
好的,我明白了,但是
column中的render(超链接)呢? @大卫康拉德
标签: javascript html json datatables