18

jquery のデータテーブル プラグインで列 ID を取得する方法 データベースの更新には列 ID が必要です。

4

8 に答える 8

23

fnGetPosition

DOM 要素から特定のセルの配列インデックスを取得します。fnGetData() と組み合わせて使用​​するのが最適です。

入力パラメータ:

nNode : 位置を見つけたいノード。これは、テーブルの「TR」行または「TD」セルのいずれかです。戻りパラメータは、この入力に依存します。

戻りパラメータ:

int または array [ int, int, int ] : ノードがテーブル行 (TR) の場合、戻り値は aoData オブジェクト内の行のインデックスを持つ整数になります。ノードがテーブル セル (TD) の場合、戻り値は [ aoData インデックス行、列インデックス (非表示行を除く)、列インデックス (非表示行を含む)] の配列になります。

コード例:

$(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から

于 2010-03-05T02:09:39.927 に答える
11

上記のdatatables.netサイトからのストックアンサーは役に立たず、質問に答えなかったと思います。

neko_ime は、選択したアイテムの列に対応する列ヘッダーの値を取得したいと考えています (これはおそらくテーブルの列名と同じか、ユーザーがテーブル ヘッダーとデータベース テーブルの間のマッピングを持っているためです)。

特定のセルの sTitle (列名の値) を取得する方法は次のとおりです。

(すべての行の最初の列に主キーがあり、iFixedColumns が 1 である ColReorder で可動列を使用している場合でも、そのキーを最初の列に保持するように注意してください。私のデータテーブルは 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 を使用しているため、これは私が自分で理解しなければならなかったことです。

于 2011-05-27T17:46:48.037 に答える
5

上記のコード スニペットは、実際に、特定の状況でこの問題を解決するのに役立ちました。これが私のコードです:

// 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;
}
于 2010-05-12T15:34:11.760 に答える
3

行をクリックした後にIDを取得する方法の例を次に示します

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

テーブル内のすべての 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]]);
});

助けてほしい!

于 2012-09-12T16:11:29.947 に答える
1

このような単純な質問には、優れた単純な jQuery ソリューションが必要です。

IDが行0にあり、たとえば行5でアクションを実行するときにアクセスしたいとします

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

これは、フィルターとページングされた結果でも機能することに注意してください。

ストックアンサーはあまり役に立たなかった@fbasに同意します。

于 2011-11-13T21:07:00.277 に答える
0

私の解決策は次のとおりです。主キーを最初の列にします-これは「表示」または「非表示」に設定できます。私の編集リンクと削除リンクは、行の最後から 2 列目と最後の列にあります。それぞれ「編集」と「削除」の 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() は、主キー (data[0]) をリンク href の末尾に追加するだけです (それが必要な場合は何でも)。これは表のレンダリング前に発生するため、ページネーションでも機能します。

于 2014-09-16T15:56:04.563 に答える