2012-04-12 56 views
1

我想鏈接來自特定列的項目,但每個鏈接將從json字符串中鏈接到不同的id。不幸的是我找不到使用API​​來做到這一點的方式(我知道有很多方法可以在不使用API​​的情況下做到這一點),但我正在尋找一種方法來鏈接列中的項目(每一個與一個特定的鏈接id)。JQuery DataTables鏈接項目

因此,這裏是我的代碼,我使用getJSON從服務器獲取JSON,我從這個JSON數據加載到表是這樣的:

$.getJSON("http://url.from/method?parameter=foo&callback=?", function(data) 
    { 
     var total = 0; 
     $("#table_body").empty(); 
     var oTable = $('#mytable').dataTable(
      { 
       "sPaginationType" : "full_numbers", 
       "aaSorting": [[ 0, "asc" ]] 
      }); 

     oTable.fnClearTable(); 

     $.each(data, function(i, item) 
     { 
      oTable.fnAddData(
       [ 
        item.contact_name, 
        item.contact_email 
       ] 
      ); 
     }); 
    }); 

我想要做什麼,是每行將contact_name鏈接到它的id,該鏈接也位於JSON中,並且可以通過使用item.contact_id在此$.each循環內進行訪問。

有沒有辦法做到這一點使用DataTables API,如果是的話,你能解釋我,並提供一個很好的資源,這將有助於我呢?

OBS:我使用JSONP

感謝。


與我的新代碼更新:

錯誤現在的問題是,我得到當我點擊的ID,但由於這樣的事實,我處理$.each循環內的行,對於任何我點擊的行,它總是會得到最後處理的行的id

var options = 
     { 
      "sPaginationType" : "full_numbers", 
      "aaSorting": [[ 0, "asc" ]], 
      "aoColumns": [{ 
       "sTitle": 'Name', 
       "sClass": "dtName", 
      }, { 
       "sTitle": 'Email', 
       "sClass": "dtEmail", 
      }, { 
       "bVisible": false 
      }], 
     } 

     var oTable = $('#table').dataTable(options); // Creates a new instance of the DataTable 

     oTable.fnClearTable(); 

     $.each(data, function(i, item) 
     { 

      oTable.fnAddData(
       [ 
        item.contact_name , 
        item.contact_email, 
        item.contact_id 
       ] 
      ); 

      var rowData = oTable.fnGetData(i); // fetch all the ids into this array 
      $('#table tbody tr').click(function() 
      { 
       window.location.href = "/panel/contacts/"+rowData[2]; 
      }); 
     }); 

回答

2

試試:

var options = { 
    "sPaginationType" : "full_numbers", 
    "aaSorting": [[ 0, "asc" ]], 
    "aoColumns": [{ 
     "sTitle": 'Name', 
     "sClass": "dtName", 
    }, { 
     "sTitle": 'Email', 
     "sClass": "dtEmail", 
    }, { 
     "bVisible": false 
    }], 
} 
var oTable = $('#mytable').dataTable(options); 

此表不會顯示ID列但你可以得到它如下面的代碼:

var rowData = oTable.fnGetData(rowNode); 

var rowData = oTable.fnGetData(0); // for the first one 

console.log(rowData[0]); 

你不能通過jQuery獲取它,因爲它沒有顯示。

編輯:對不起,我忘了一兩件事,當你使用AddData把item.contact_id第三位:

oTable.fnAddData([ 
    item.contact_name, 
    item.contact_email, 
    item.contact_id 
]); 

如果你想獲得單擊事件ID做到這一點:

jQuery('#mytable tbody tr').live('click', function() { 
    var selectedRow = oTable.fnGetData(this), 
     url = "/yourUrl/" + selectedRow[2]; 

    window.location.replace(url); 
}); 
+0

等等..此代碼中的JSON項目在哪裏?我可以看到你正在加載一些文本並翻譯它,但是在哪裏加載(正如我之前在代碼中顯示的)item.contact_name和item.contact_email? – rogcg 2012-04-12 23:56:08

+0

對不起,我習慣把翻譯放在我的js上,我會編輯它。 – 2012-04-12 23:57:55

+0

所以,你會加載在同一個地方,只是修改你的功能。 – 2012-04-12 23:58:55