2012-04-12 58 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