dataTables make clickable to link

2019-05-23 14:54发布

I have a dataTables table at http://communitychessclub.com/test.php

My problem is I need to make an entire table row clickable to a link based on a game#. The table lists games and user should click on a row and the actual game loads.

I am unable to understand the previous solutions to this problem. Can somebody please explain this in simple terms?

I previously did this at http://communitychessclub.com/games.php (but that version is too verbose and does disk writes with php echo) with

echo "<tr onclick=\"location.href='basic.php?game=$game'\" >"; 

<script>$(document).ready(function() {
$('#cccr').dataTable( {
    "ajax": "cccr.json",

   "columnDefs": [
        {
            "targets": [ 0 ],
            "visible": false,
        }
    ],

    "columns": [
        { "data": "game" },
        { "data": "date" },
        { "data": "event" },
        { "data": "eco" },
        { "data": "white_rating" },
        { "data": "white" },
        { "data": "black_rating" },
        { "data": "black" }
    ]
    } );
  } );</script>

"cccr.json" looks like this and is fine:

{
"data": [
{
"game": "5086",
"date": "09/02/2013",
"event": "135th NYS Ch.",
"eco": "B08",
"white": "Jones, Robert",
"white_rating": "2393",
"black": "Spade, Sam",
"black_rating": "2268"
},
...

标签: datatables
1条回答
The star\"
2楼-- · 2019-05-23 15:15

You can do it this way:

Use fnRowCallback to add a game-id data-attribute to your datatable rows

...
    { "data": "black" }
    ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            //var id = aData[0];
            var id = aData.game;
            $(nRow).attr("data-game-id", id);
            return nRow;
        }

This will give each row in your table a game id attribute e.g:

<tr class="odd" data-game-id="5086">

Then create a javascript listener for the click event and redirect to the game page passing the game id taken from the tr data-attribute:

$('#cccr tbody').on('click', 'tr', function () {
   var id = $(this).data("game-id");
   window.location = 'basic.php?game=' + id;
}
查看更多
登录 后发表回答