【发布时间】:2016-01-18 13:05:09
【问题描述】:
我正在尝试使用 DataTables 创建一个 JSON 传递的表,并在单击表中的某些链接时让该表执行“操作”。链接并不总是存在,因此它们需要动态生成。 我刚刚开始使用 jQuery,我无法弄清楚我所说的“附加”到正确元素的回调。
这是一个示例 HTML 页面,带有一个动态生成的“向上”链接(在普通的旧 JS 中相当幼稚)。这个想法是点击该链接将例如生成一个警报,显示您单击了哪一行,以及上面的行。最终目标是能够使用链接/按钮向上或向下移动行。
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Show a re-orderable list</title>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" />
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.11.3.min.js"> </script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"> </script>
<script type="text/javascript" class="init">
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "foo_data.txt",
"columnDefs": [
{
"render": function ( data, type, row ) {
var extra_text = "";
if( data === "Queued" ) {
extra_text = ' <a href="#" class="up_queue">Up</a> Down ';
}
return data +' ('+ row[3]+')' + extra_text;
},
"targets": 1
},
{ "visible": false, "targets": [ 3 ] }
]
} );
$(".up_queue").on('click', function() {
var mydata = table.row( this ).data();
var uprow = table.row( this ).index() - 1;
var updata = table.row( uprow) .data();
alert( 'You clicked on '+mydata[0]+ ' ' +updata[0] +' row' );
});
} );
</script>
<body>
<div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Job ID</th>
<th>Status</th>
<th>Name</th>
<th>Elapsed Time</th>
<th>Options</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
基本上问题是“向上”链接什么都不做......我想知道点击了哪一行,以及点击者正上方的行的索引。有什么想法吗?
这是可以通过 AJAX 提供的相关数据 foo_data.txt:
{
"data":
[["101","Finished","Static","3 days",""],
["102","Queued","Moveable1","--",""],
["103","Queued","Moveable2","--",""],
["104","Queued","Moveable3","--",""],
["105","Queued","Moveable4","--",""],
["106","Queued","Moveable5","--",""],
["107","Queued","Moveable6","--",""]]}
【问题讨论】:
标签: javascript jquery html ajax datatables