So I'm using DataTables to pull data from a local JSON file into a table. I'm trying to apply hyperlinks to every cell in a particular column but the URL itself is made up of data that is stored in the JSON, but I don't display it in the table because the user doesn't need to see it.
Simplified example:
Table:
| Name |
-----------
| Apple |
| Pear |
| Orange |
Generated from:
{Fruits:[
{
"Name":"Apple",
"id" :"123"
},
{
"Name":"Pear",
"id" :"456"
},
{
"Name":"Orange",
"id" :"789"
}
]}
So Pear would have a link to something like http://example.com/?pageid=456
without "id" ever being displayed anywhere in the table.
Something like <a href="http://example.com/?pageid={{id}}">{{name}}</a>
would be how I'd do it in handlebars but alas, I'm using DataTables.
I thought about putting the ID for the URL in the table and then just hiding it so I can just grab it out the DOM using jQuery but that feels hacky to me.
You can use fnRowCallback
in the options when you initialize the dataTable
:
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var a = $('<a />').attr({
"class": "some-class",
"id": "fruit" + aData.id,
"href": "http://example.com/?pageid=" + aData.id
}).text(aData.Name);
$('td:eq(0)', nRow).empty().append(a); //assumes you want this in the first column
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.