jQuery 获取数据表中选定行的第一列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32307818/
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
Get selected rows first column value in datatable
提问by user3667960
$('.example tbody').on('click', 'tr', function (){
var id = this.id;
var index = $.inArray(id, selected);
if (index === -1)
{
selected.push(id);
} else
{
selected.splice(index, 1);
}
$(this).toggleClass('selected');
});
$('#btn').click(function (){
var dataArr = [];
var rowCount = table.rows('.selected').data().length;
alert(rowCount);
});
Here is the code for select multiple rows. On clicking the button I need to get the selected rows first column value and store in array dataArr[]. Please help me to fix this.
这是选择多行的代码。单击按钮时,我需要获取所选行的第一列值并存储在数组 dataArr[] 中。请帮我解决这个问题。
回答by Guruprasad Rao
Try this:
尝试这个:
$('#btn').click(function (){
var dataArr = [];
$.each($("#example tr.selected"),function(){ //get each tr which has selected class
dataArr.push($(this).find('td').eq(0).text()); //find its first td and push the value
//dataArr.push($(this).find('td:first').text()); You can use this too
});
console.log(dataArr);
});
UPDATE
更新
You can get using some native functions of dataTables
too as below:
您也可以使用一些本机功能,dataTables
如下所示:
$('#btn').click(function (){
var dataArr = [];
var rows = $('tr.selected');
var rowData = table.rows(rows).data();
$.each($(rowData),function(key,value){
dataArr.push(value["name"]); //"name" being the value of your first column.
});
console.log(dataArr);
});
回答by Dinand
Guruprasad code (perfect) with small handy updates.
Guruprasad 代码(完美),带有方便的小更新。
var table= $('#YourTableName').DataTable();
$('#button').click(function () {
var arr = [];
$.each(table.rows('.selected').data(), function() {
arr.push(this["ColomnName"]);
});
});