Подтвердить что ты не робот

JQuery - datatables, как получить идентификатор столбца

Как получить идентификатор столбца в datatable plugin для jquery Мне нужен идентификатор столбца для обновления в базе данных.

4b9b3361

Ответ 1

fnGetPosition

Получить индексы массивов определенного ячейки из него элемента DOM. Самые популярные в сочетании с fnGetData().

Входные параметры:

nNode: node вы хотите найти положение. Это мой либо "ТР", строка или ячейка "TD" из таблицы. параметр возврата зависит от этого вход.

Возвращаемый параметр:

int или array [int, int, int]: if node представляет собой строку таблицы (TR), затем возвращаемое значение будет целым числом с индекс строки в aoData объект. Если node является ячейкой таблицы (TD), тогда возвращаемое значение будет массив с [aoData index row, column индекс (дисконтирование скрытых строк), столбец index (включая скрытые строки)].

Пример кода:

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

От datatables.net

Ответ 2

Я думаю, что ответ на акции выше с сайта datatables.net не помог и не ответил на вопрос.

Я считаю, что neko_ime хочет получить значение заголовка столбца, соответствующее столбцу выбранного элемента (так как это, вероятно, совпадает с именем столбца в таблице или пользователь имеет сопоставление между заголовком таблицы и таблицей базы данных).

вот как вы получаете sTitle (значение имени столбца) для данной ячейки

(обратите внимание, что у меня есть свой первичный ключ в первом столбце каждой строки, и убедитесь, что даже если с помощью перемещаемых столбцов с ColReorder с iFixedColumns равно 1, чтобы сохранить этот ключ в первом столбце, на мой datatable ссылается 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+'"');

Это то, что я должен был выяснить сам, поскольку я использую JEditable, чтобы позволить пользователям редактировать ячейки в таблице.

Ответ 3

Фрагмент кода выше действительно помог мне решить эту проблему для моей конкретной ситуации. Здесь мой код:

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

Ответ 4

Вот пример того, как получить идентификатор после нажатия на строку

$('#example tbody tr').live('click', function() {
         var row = example .fnGetData(this);
         id=row['id'];//or row[0] depend of situation
         function(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]]);
});

надежды на помощь!

Ответ 5

Простой вопрос, подобный этому, заслуживает хорошего простого решения jQuery.

Предположим, что ваш идентификатор находится в строке 0 и вы хотите получить к нему доступ при выполнении действия в строке 5, например

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

Обратите внимание, что это работает и для фильтра, и для постраничных результатов.

Я согласен с ответом @fbas на то, что это не очень полезно.

Ответ 6

    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>

Ответ 7

Мое решение было следующим: иметь первичный ключ в качестве 1-го столбца - это можно установить как "видимое" или нет. Мои ссылки на редактирование и удаление находятся в последнем, но одном и последнем столбцах в строке - у них есть классы css 'edit' и 'delete' соответственно. Затем, используя 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() просто добавляет первичный ключ (данные [0]) в конец ссылок href (независимо от того, что может потребоваться). Это происходит с предварительным отображением таблицы, и поэтому также работает над разбиением на страницы.

Ответ 8

У меня был один и тот же вариант использования, и я превратил свой код в плагин datatables.net. Репо находится здесь: DataTables Плагин CellEdit

Основная инициализация выполняется быстро и просто:

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