2010-03-05 17 views

Odpowiedz

23

fnGetPosition

Get indeksy tablicy konkretnego celi jest elementem Dom. Najlepiej używać w połączeniu z fnGetData().

parametry wejściowe:

nNode: węzeł chcesz znaleźć pozycję się. To może być wiersz "TR" lub komórka "TD" z tabeli. Parametr powrotu zależy od tego wejścia . Parametr

powrotu:

Int lub tablica [Int int int] Jeśli węzeł jest wiersz tabeli (TR), a następnie wartość powrotu będzie liczbą całkowitą indeks wiersza w obiekcie aoData . Jeżeli węzeł jest komórka tabeli (TD), a następnie wartość powrotu będzie tablicę z [aoData indeksu rzędu kolumna indeksu (dyskonta ukryte rzędów), w kolumnie indeksu (włącznie z ukrytym rzędów)].

przykładem Kod:

$(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(); 
}); 

Od datatables.net

5

Fragment kodu powyżej faktycznie pomógł mi rozwiązać ten problem dla mojej konkretnej sytuacji. Oto mój kod:

// 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; 
} 
+0

To jest dla jQuery wartości elementu datatable ukrytej kolumny, ale oczywiście można uzyskać wartość dowolnej kolumny w datatable. – Solburn

+0

Super użyteczny kod! Dziękuję Ci! – Peter

10

Myślę, że powyższa odpowiedź na pytania ze strony datatables.net nie była pomocna i nie odpowiedział na pytanie.

Wierzę, że neko_ime chce uzyskać wartość nagłówka kolumny odpowiadającą kolumnie wybranego elementu (ponieważ jest prawdopodobnie taka sama jak nazwa kolumny w tabeli lub użytkownik ma odwzorowanie między nagłówkiem tabeli i bazą danych stół).

oto jak masz sTitle (nazwa kolumny wartości) dla danej komórce

(zauważ, mam klucz podstawowy w pierwszej kolumnie każdego wiersza, i upewnić się, że nawet w przypadku korzystania z ruchomych kolumn z ColReorder że iFixedColumns wynosi 1, aby zachować ten klucz w pierwszej kolumnie mój DataTable odwołuje oTable jestem przy założeniu, że mam odniesienie DOM komórki, które ja nazywam „target” poniżej):..

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+'"'); 

To jest coś, co musiałem sam wymyślić, ponieważ używam JEditable, aby umożliwić użytkownikom edycję komórek w ta ble.

1

Proste pytanie, takie jak to, zasługuje na dobre proste rozwiązanie jQuery.

zakładamy, że id jest rzędu 0 i chcesz uzyskać do niego dostęp podczas wykonywania działań w wierszu 5 na przykład

$('td:eq(5)').click(function(){ 
    var id = $(this).parent().find('td:eq(0)').html(); 
    alert('The id is ' + id); 
}); 

Uwaga ta działa na filtrze i pager wyniki również.

Zgadzam się z @fbas odpowiedź na pytanie nie była naprawdę pomocna.

+0

To spowodowało, że zastanawiałem się przez chwilę, myślę, że kiedy nas programiści (OK, może tylko ja) widzimy wtyczki i biblioteki, spróbujmy rozwiązać nasze problemy. – Sydwell

+1

Taki sam komentarz, ale pytanie dotyczy kolumny id, a nie wiersza – Mike

3

Oto przykład, jak uzyskać identyfikator po kliknięciu w rzędzie

$('#example tbody tr').live('click', function() { 
     var row = example .fnGetData(this); 
     id=row['id'];//or row[0] depend of situation 
     function(id); 
}); 

Jeśli potrzebujesz cały id w tabeli trzeba użyć kodu:

$(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]]); 
}); 

mam nadzieję, pomoc!

+0

, ale pytanie dotyczy kolumny id, a nie wiersza – Mike

0

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> 
+0

Niestety, zawsze ta sama uwaga, ale pytanie dotyczy kolumny id, a nie wiersza – Mike

0

Moje rozwiązanie było następujące: mieć klucz podstawowy jest 1. kolumny - to może być ustawiona jako „widoczny”, czy nie. Moje linki do edycji i usuwania znajdują się w ostatniej, ale ostatniej kolumnie w wierszu - mają odpowiednio klasy css "edit" i "delete". Następnie za pomocą rowCallBack, wywołać funkcję tak:

<!-- 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() po prostu dołącza klucz podstawowy (dane [0]) do końca href linków (cokolwiek to może być konieczne). Dzieje się to renderowanie przed tabelą, a zatem działa również w przypadku stronicowania.

0

Miałem ten sam przypadek użycia i skończyłem na tym, że przeniosłem swój kod do wtyczki datatables.net. Repo jest tutaj: DataTables CellEdit Plugin

Podstawowym inicjalizacji jest szybkie i proste:

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()); 
} 
Powiązane problemy