Jquery - Add hyperlink to datatables

2019-06-05 03:31发布

问题:

Using the DataTable plugin I am able to generate a table just fine but I want a custom hyperlink on one of the columns that links to another page but taking information from the rest of the row...for example in row 1 I want a hyperlink: http://url/?data['imdata'][i]['faultInst']["attributes"]["code"] or something like that. I've seen a lot of complicated examples from other forms but couldn't get it to work. Looking for the simplest solution as this is a side project and I need it to be completed.

$(document).ready(function(){

        $.getJSON('/static/faults.json', function (data) {

            var test = $('#table5').DataTable({
            });

            var tr;
            for (var i = 0; i < data["totalCount"]; i++) {
              test.row.add([
                  data['imdata'][i]['faultInst']["attributes"]["code"],
                  data['imdata'][i]['faultInst']["attributes"]["cause"],
                  data['imdata'][i]['faultInst']["attributes"]["descr"],
                  data['imdata'][i]['faultInst']["attributes"]["created"],
                  data['imdata'][i]['faultInst']["attributes"]["changeSet"],
                  data['imdata'][i]['faultInst']["attributes"]["childAction"],
                  data['imdata'][i]['faultInst']["attributes"]["dn"],
                  data['imdata'][i]['faultInst']["attributes"]["domain"],
                  data['imdata'][i]['faultInst']["attributes"]["highestSeverity"],
                  data['imdata'][i]['faultInst']["attributes"]["lastTransition"],
                  data['imdata'][i]['faultInst']["attributes"]["lc"],
                  data['imdata'][i]['faultInst']["attributes"]["occur"],
                  data['imdata'][i]['faultInst']["attributes"]["origSeverity"],
                  data['imdata'][i]['faultInst']["attributes"]["prevSeverity"],
                  data['imdata'][i]['faultInst']["attributes"]["rule"],
                  "test",
                  //data['imdata'][i]['faultInst']["attributes"]["Severity"],
                  data['imdata'][i]['faultInst']["attributes"]["subject"],
                  data['imdata'][i]['faultInst']["attributes"]["type"],
                  //data['imdata'][i]['faultInst']['attributes']["ack"]
                  "test",
                  "test"
              ])
            }

            test.draw();
        });
    });

回答1:

When you have a setup like this, just avoid to define data, by that you get the proper value you can turn into a link. dataTables know which data it should pass to the render function by the targets value. Example :

var table = $('#example').DataTable({
    columnDefs : [
      { targets : [0],
        render : function(data) {
          return '<a href="'+data+'" target_blank>'+data+'</a>'
        } 
      }
    ]
})  

table.row.add(['https://example.com', 'david', 'programmer']).draw()

demo -> http://jsfiddle.net/47k7nhkb/