简体   繁体   中英

Return jQuery object from DataTables render function

I would like to return a jQuery object inside of a render function. Since that doesn't seem possible, the code below is as close as I got.

Is this an acceptable solution? When is type type called? I can't seem to find any info about it in the docs.

var dataSet = [
    ['Trident','Internet Explorer 4.0','Win 95+','4','X'],
    ['Trident','Internet Explorer 5.0','Win 95+','5','C'],
    ['Trident','Internet Explorer 5.5','Win 95+','5.5','A'],
    ['Trident','Internet Explorer 6','Win 98+','6','A'],
    ['Trident','Internet Explorer 7','Win XP SP2+','7','A'],
    ['Trident','AOL browser (AOL desktop)','Win XP','6','A']
];

$('#example').dataTable( {
    columns: [
        { 
            "title": "Engine", 
            "className": "foo", 
            "render": function ( data, type, row, meta ) {

                var $td = $('#example').DataTable().cell(meta.row, meta.col).nodes().to$();

                if(type === 'type'){
                    var $a = $('<a href="#"/>').data({ data: row }).text('foo');
                    $td.html($a);
                }


                return data;
          },
        },
        { "title": "Browser" },
        { "title": "Platform" },
        { "title": "Version", "className": "center" },
        { "title": "Grade", "className": "center" }
    ],

    data: dataSet
});

http://jsfiddle.net/y3fnvzad/7/

When function is specified for render option, DataTables will call render function multiple times for the different data types that it needs - sorting, filtering and display.

Also, per documentation:

The return value from the function is what will be used for the data requested.

So you need to return a string (not jQuery object) that will contain data for type of operation requested.

If you would like to construct a link using jQuery, you need to return HTML string when type equals to display , see the code excerpt below:

        "render": function ( data, type, row, meta ) {
            if(type === 'display'){
                return $('<a href="#"/>')
                   .text('foo')
                   .wrap('<div></div>')
                   .parent()
                   .html();
            } else {
                return data;
            }
      },

UPDATE:

It doesn't makes sense to assign data to the element using jQuery data() since we're returning HTML string not jQuery object. In the example below I have demonstrated how you can access row data, when link is clicked.

$('#example tbody').on('click', 'a', function(){
    // Get row data 
    console.log($('#example').DataTable().row($(this).closest('tr')).data());
});

See this JSFiddle for demonstration.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM