我试图让我的 DataTable 中的行可以点击。单击时我想将用户导航到另一个页面。
当我执行脚本并单击行时,脚本总是将我导航到 ./test/data.php?id=1
,这是我要用于第一行的页面。同一脚本在所有行中都处于事件状态。
有人知道为什么我的脚本将链接粘贴到所有行的第一行吗?我该如何解决这个问题?
这是我的脚本:
<script type="text/javascript">
$( document ).ready(function() {
$('#grid1').DataTable({
"bprocessing": true,
"serverSide": true,
"ajax": {
"url": "response2.php",
"type": "POST",
"error": function(){
$("#grid_processing").css("display","none");
}
},
"columnDefs": [
{ "targets": 1, "render": function ( data, type, full, meta ) { return '<b>'+data+'</b>'} },
{ "targets": 3, "render": function ( data, type, full, meta ) { return '<i>'+data+'</i>'} },
{ "targets": 6, "render": function ( data, type, full, meta ) { return '<a href="./test/data.php?id='+data+'"></a>'; } }
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#grid1').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
});
</script>
编辑 1:
response2.php:
<?php
include_once("connection.php");
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
$columns = array(
0 => 'name',
1 => 'address',
2 => 'number',
3 => 'city',
4 => 'country',
5 => 'id'
);
$where = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( id LIKE '".$params['search']['value']."%' ";
$where .=" OR name LIKE '".$params['search']['value']."%')";
}
if (!empty($where) ) {
$where .= "AND user_id='1' ";
} else {
$where .= "WHERE user_id='1' ";
}
$sql = "SELECT name, address, number, city, country, id FROM customers ";
$sqlTot .= $sql;
$sqlRec .= $sql;
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY id DESC LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data
);
echo json_encode($json_data);
?>
最佳答案
您需要为每一行初始化 click
监听器。
您可以指定设置 URL 或 URL 参数的列索引,在此示例中,索引为 6,与您的原始示例相同。
已编辑:
用这个替换你的点击监听器。此脚本将检测您单击了哪一行,并为链接使用正确的行:
<script type="text/javascript">
$(document).ready(function() {
var table = $('#grid1').DataTable();
$('#grid1').on( "click", "td", function (e) {
var rowIdx = table.row( this ).index();
var sData = table.cells({ row: rowIdx, column: 6 }).data()[0];
if (sData && sData.length) {
location.href = './test/data.php?id=' + sData;
}
});
});
</script>
一个好主意是像@ygorbunkov 的回答那样向该行添加一些 CSS 样式,这样该行将显示为一个链接。
关于javascript - 使数据表中的行可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54619076/