Here is a self-contained demo that you can save to an HTML file and then run in a browser for yourself:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%"></table>
</div>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').DataTable( {
ajax: {
method: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
dataSrc: ""
},
"columns": [
{ "title": "ID", "data": "id" },
{ "title": "Title", "data": "title" },
],
"initComplete": function () {
var api = this.api();
api.$('tr').click( function () {
var id = api.row( this ).data().id;
var newUrl = "https://jsonplaceholder.typicode.com/posts/" + id
window.open(newUrl);
} );
}
} );
} );
</script>
</body>
</html>
This demo uses the test JSON data made available at JSONPlaceholder. To start with, DataTables uses the following to load data into the HTML table:
ajax: {
method: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
dataSrc: ""
}
Because the JSON returned from JSONPlaceholder does not have a named array (its outer container is simply [...]
), we need to tell DataTables about this, using dataSrc: ""
. Your data may be structured differently.
Once the DataTable object has been initialized, we create the following function:
"initComplete": function () {
var api = this.api(); // gives us access to the DataTables API from within the table itself
api.$('tr').click( function () { // register a row-level click event
var id = api.row( this ).data().id; // see notes below
var newUrl = "https://jsonplaceholder.typicode.com/posts/" + id
window.open(newUrl);
} );
}
The following line...
var id = api.row( this ).data().id;
...uses the DataTables API row() call to grab the clicked row, and then find the value for the "id" field in that row. This "id" name comes from the original JSON data we loaded.
The JSONPlaceholder web site has dummy data for each "post" record. The new URL we construct takes us to that JSON record.
There is certainly more than one way to achieve your end goal.
In this specific case, there was no need for me to use the "select" extension that you mentioned in your comments. But that is also one other approach you can use.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…