jQuery - 数据表,如何获取列 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2384102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - datatables, how to get column id
提问by neko_ime
How to get a column id in datatable plugin for jquery I need column id for the update in database.
如何在 jquery 的数据表插件中获取列 id 我需要列 id 来更新数据库。
回答by James Kolpack
fnGetPosition
获取位置
Get the array indexes of a particular cell from it's DOM element. Best used in combination with fnGetData().
从它的 DOM 元素中获取特定单元格的数组索引。最好与 fnGetData() 结合使用。
Input parameters:
输入参数:
nNode : the node you want to find the position of. This my be either a 'TR' row or a 'TD' cell from the table. The return parameter depends on this input.
nNode :要查找位置的节点。这可以是表格中的“TR”行或“TD”单元格。返回参数取决于此输入。
Return parameter:
返回参数:
int or array [ int, int, int ] : if the node is a table row (TR) then the return value will be an integer with the index of the row in the aoData object. If the node is a table cell (TD) then the return value will be an array with [ aoData index row, column index (discounting hidden rows),column index (including hidden rows) ].
int 或 array [ int, int, int ] :如果节点是表行 (TR),则返回值将是一个整数,其中包含 aoData 对象中该行的索引。如果节点是表格单元格 (TD),则返回值将是一个数组,其中包含 [aoData 索引行、列索引(隐藏隐藏行)、列索引(包括隐藏行)]。
Code example:
代码示例:
$(document).ready(function() {
$('#example tbody td').click( function () {
/* Get the position of the current data from the node */
var aPos = oTable.fnGetPosition( this );
/* Get the data array for this row */
var aData = oTable.fnGetData( aPos[0] );
/* Update the data array and return the value */
aData[ aPos[1] ] = 'clicked';
this.innerHTML = 'clicked';
} );
/* Init DataTables */
oTable = $('#example').dataTable();
} );
From datatables.net
回答by fbas
I think the stock answer above from datatables.net site was not helpful and didn't answer the question.
我认为上面来自 datatables.net 站点的股票答案没有帮助,也没有回答问题。
I believe neko_ime wants to get the column header value corresponding to the column of the selected item (since this is probably the same as the column name in the table, or the user has a mapping between the table header and the database table).
相信neko_ime是想获取选中项的列对应的列头值(因为这可能和表中的列名相同,或者用户有表头和数据库表的映射关系)。
here is how you get the sTitle (column name value) for a given cell
这是获取给定单元格的 sTitle(列名值)的方法
(note I have my primary key in first column of every row, and have made sure that even if using movable columns with ColReorder that iFixedColumns is 1, to keep that key in the first column. my datatable is referenced by oTable. I am assuming that I have the cell DOM reference, which I call 'target' below):
(注意我在每一行的第一列都有我的主键,并确保即使使用带有 ColReorder 的可移动列 iFixedColumns 为 1,以将该键保留在第一列中。我的数据表由 oTable 引用。我假设我有单元格 DOM 引用,我在下面将其称为“目标”):
var value = target.innerHTML;
var ret_arr = oTable.fnGetPosition( target ); // returns array of 3 indexes [ row, col_visible, col_all]
var row = ret_arr[0];
var col = ret_arr[1];
var data_row = oTable.fnGetData(row);
var primary_key = data_row[0];
var oSettings = oTable.fnSettings(); // you can find all sorts of goodies in the Settings
var col_id = oSettings.aoColumns[col].sTitle; //for this code, we just want the sTitle
// you now have enough info to craft your SQL update query. I'm outputting to alert box instead
alert('update where id="'+primary_key+'" set column "'+col_id+'" ('+row+', '+col+') to "'+value+'"');
This is something I had to figure out myself, since i'm using JEditable to allow users to edit cells in the table.
这是我必须自己弄清楚的事情,因为我使用 JEditable 来允许用户编辑表格中的单元格。
回答by Solburn
The code snippet above actually helped me solve this issue for my particular situation. Here's my code:
上面的代码片段实际上帮助我针对我的特定情况解决了这个问题。这是我的代码:
// My DataTable
var oTable;
$(document).ready(function() {
/* You might need to set the sSwfPath! Something like:
* TableToolsInit.sSwfPath = "/media/swf/ZeroClipboard.swf";
*/
TableToolsInit.sSwfPath = "../../Application/JqueryPlugIns/TableTools/swf/ZeroClipboard.swf";
oTable = $('#tblFeatures').dataTable({
// "sDom": '<"H"lfr>t<"F"ip>', // this is the standard setting for use with jQueryUi, no TableTool
// "sDom": '<"H"lfrT>t<"F"ip>', // this adds TableTool in the center of the header
"sDom": '<"H"lfr>t<"F"ip>T', // this adds TableTool after the footer
// "sDom": '<"H"lfrT>t<"F"ip>T', // this adds TableTool in the center of the header and after the footer
"oLanguage": { "sSearch": "Filter this data:" },
"iDisplayLength": 25,
"bJQueryUI": true,
// "sPaginationType": "full_numbers",
"aaSorting": [[0, "asc"]],
"bProcessing": true,
"bStateSave": true, // remembers table state via cookies
"aoColumns": [
/* CustomerId */{"bVisible": false },
/* OrderId */{"bVisible": false },
/* OrderDetailId */{"bVisible": false },
/* StateId */{"bVisible": false },
/* Product */null,
/* Description */null,
/* Rating */null,
/* Price */null
]
});
// uncomment this if you want a fixed header
// don't forget to reference the "FixedHeader.js" file.
// new FixedHeader(oTable);
});
// Add a click handler to the rows - this could be used as a callback
// Most of this section of code is from the DataTables.net site
$('#tblFeatures tr').click(function() {
if ($(this).hasClass('row_selected')) {
$(this).removeClass('row_selected');
}
else {
$(this).addClass('row_selected');
// Call fnGetSelected function to get a list of selected rows
// and pass that array into fnGetIdsOfSelectedRows function.
fnGetIdsOfSelectedRows(fnGetSelected(oTable));
}
});
function fnGetSelected(oTableLocal) {
var aReturn = new Array();
// fnGetNodes is a built in DataTable function
// aTrs == array of table rows
var aTrs = oTableLocal.fnGetNodes();
// put all rows that have a class of 'row_selected' into
// the returned array
for (var i = 0; i < aTrs.length; i++) {
if ($(aTrs[i]).hasClass('row_selected')) {
aReturn.push(aTrs[i]);
}
}
return aReturn;
}
// This code is purposefully verbose.
// This is the section of code that will get the values of
// hidden columns in a datatable
function fnGetIdsOfSelectedRows(oSelectedRows) {
var aRowIndexes = new Array();
var aRowData = new Array();
var aReturn = new Array();
var AllValues;
aRowIndexes = oSelectedRows;
// The first 4 columns in my DataTable are id's and are hidden.
// Column0 = CustomerId
// Column1 = OrderId
// Column2 = OrderDetailId
// Column3 = StateId
// Here I loop through the selected rows and create a
// comma delimited array of id's that I will be sending
// back to the server for processing.
for(var i = 0; i < aRowIndexes.length; i++){
// fnGetData is a built in function of the DataTable
// I'm grabbing the data from rowindex "i"
aRowData = oTable.fnGetData(aRowIndexes[i]);
// I'm just concatenating the values and storing them
// in an array for each selected row.
AllValues = aRowData[0] + ',' + aRowData[1] + ',' + aRowData[2] + ',' + aRowData[3];
alert(AllValues);
aReturn.push(AllValues);
}
return aReturn;
}
回答by Oibaf it
Here an example of how to get an id after clicking on the row
这是单击行后如何获取 id 的示例
$('#example tbody tr').live('click', function() {
var row = example .fnGetData(this);
id=row['id'];//or row[0] depend of situation
function(id);
});
If you need all the id in a table you have to use a code like this:
如果您需要表中的所有 id,则必须使用如下代码:
$(exampleTable.fnGetNodes()).each(function() {
var aPos = exampleTable.fnGetPosition(this);
var aData = exampleTable.fnGetData(aPos[0]);
aData[aPos[0]] = this.cells[0].innerHTML;
IdSet.push(aData[aPos[0]]);
});
hope help!
希望有帮助!
回答by Sydwell
A simple question like this deserves a good simple jQuery solution.
像这样的简单问题值得一个很好的简单 jQuery 解决方案。
Assume your id is on row 0 and you want to access it when performing action on row 5 for example
假设您的 id 位于第 0 行,并且您想在第 5 行执行操作时访问它,例如
$('td:eq(5)').click(function (){
var id = $(this).parent().find('td:eq(0)').html();
alert('The id is ' + id);
});
Note this works for the filter and paged results as well.
请注意,这也适用于过滤器和分页结果。
I agree with @fbas the stock answer was not really helpful.
我同意@fbas,股票答案并不是很有帮助。
回答by Zakari
var oTable;
/* Get the rows which are currently selected */ function fnGetSelected(oTableLocal) { var aReturn = new Array(); var aTrs = oTableLocal.fnGetNodes(); for (var i = 0; i < aTrs.length; i++) { if ($(aTrs[i]).hasClass('row_selected')) { aReturn.push(aTrs[i]); } } // console.log( aReturn); return aReturn; } $(function() { ///////////////// //btn_EditCustomer $('#btn_EditCustomer').on('click', function(e) { var anSelected = fnGetSelected(oTable); var rowData = oTable.fnGetData(anSelected[0]); console.log(rowData[0]); }); }); </script>
var oTable;
/* Get the rows which are currently selected */ function fnGetSelected(oTableLocal) { var aReturn = new Array(); var aTrs = oTableLocal.fnGetNodes(); for (var i = 0; i < aTrs.length; i++) { if ($(aTrs[i]).hasClass('row_selected')) { aReturn.push(aTrs[i]); } } // console.log( aReturn); return aReturn; } $(function() { ///////////////// //btn_EditCustomer $('#btn_EditCustomer').on('click', function(e) { var anSelected = fnGetSelected(oTable); var rowData = oTable.fnGetData(anSelected[0]); console.log(rowData[0]); }); }); </script>
回答by Matthew Diggins
My solution was the following: have the primary key as the 1st column - this can be set as 'visible' or not. My edit and delete links are in the last but one and last columns in the row - they have css classes of 'edit' and 'delete' respectively. Then using rowCallBack, call a function like this:
我的解决方案如下:将主键作为第一列 - 这可以设置为“可见”或不可见。我的编辑和删除链接位于行中的最后一列和最后一列 - 它们分别具有“编辑”和“删除”的 css 类。然后使用 rowCallBack,调用这样的函数:
<!-- datatables initialisation -->
"rowCallback": function( row, data ) {
setCrudLinks(row, data);
}
function setCrudLinks(row, data) {
d = $(row).find('a.delete');
d.attr('href', d.attr('href')+'/'+data[0]);
e = $(row).find('a.edit');
e.attr('href', e.attr('href')+'/'+data[0]);
}
setCrudLinks() simply appends the primary key (data[0]) to the end of the links href (whatever that might need to be). This happens pre table render, and therefore works over pagination too.
setCrudLinks() 只是将主键 (data[0]) 附加到链接 href 的末尾(无论需要什么)。这发生在表格渲染之前,因此也适用于分页。
回答by Elliott
I had the same use case and ended up spinning my code off into a datatables.net plugin. The repo is here: DataTables CellEdit Plugin
我有相同的用例,最终将我的代码转成 datatables.net 插件。存储库在这里:DataTables CellEdit Plugin
The basic initialization is quick and easy:
基本的初始化快速而简单:
table.MakeCellsEditable({
"onUpdate": myCallbackFunction
});
myCallbackFunction = function (updatedCell, updatedRow) {
var columnIndex = cell.index().column;
var columnHeader = $(table.column(columnIndex).header()).html();
console.log("The header is: " + columnHeader);
console.log("The new value for the cell is: " + updatedCell.data());
}