如何从数据表中获取所选表格单元格的值?

时间:2015-01-20 06:03:02

标签: jquery datatable

这是我的Jquery:

var oTable_salary = $('#jsontable_salary').dataTable();  //Initialize the datatable
$("#btn_ca_salary").click(function(){
    $.ajax({
        url: 'proc_php/get_salary.php',
        dataType: 'json',
        success: function(s){
            oTable_salary.fnClearTable();
            for(var i = 0; i < s.length; i++) {
             oTable_salary.fnAddData([
                        s[i][0],
                        s[i][1],
                        s[i][2],
                        s[i][3]                                     
                               ]);                                      
            } // End For                                            
        },
        error: function(e){
           alert(e.responseText);   
        }
        });
}); 

enter image description here

我想在选中时从datable获取id。我想出了这个,但它没有工作:

$('#jsontable_salary tbody tr').on('click', function (e) {
    e.preventDefault();
    var rowIndex =  $(this).closest('td')[0].text;
    alert(rowIndex);
});

2 个答案:

答案 0 :(得分:2)

尝试在此上下文中使用.find(),因为我们尝试从其父td的点击事件中检索tr值,

$('#jsontable_salary').on('click', 'tr', function (e) {
    e.preventDefault();
    var rowIndex =  $(this).find('td:eq(0)').text();
    alert(rowIndex);
});

在运行时加载的元素必须使用event delegation才能附加事件。

答案 1 :(得分:2)

你可以尝试

var rowIndex =  $(this).find('td').first().text()

您使用最近的尝试不起作用,因为最接近DOM向上遍历

相关问题