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

时间:2022-12-03 10:19:18

This my Jquery:

这是我的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);   
        }
        });
}); 

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

I want to get the id from the datable when it is selected. I came up with this but it doesn't work:

我希望在选中时从datable中获取id。我想出了这个,但它不起作用:

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

2 个解决方案

#1


2  

You can try

你可以试试

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

your attempt with closest doesn't work, as closest traverses the DOM upwards

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

#2


2  

Try to use .find() at this context since we are trying to retrieve the td value from the click event of its parent tr,

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

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

Elements that are getting loaded during the run time must use event delegation in order to attach an event with it.

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

#1


2  

You can try

你可以试试

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

your attempt with closest doesn't work, as closest traverses the DOM upwards

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

#2


2  

Try to use .find() at this context since we are trying to retrieve the td value from the click event of its parent tr,

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

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

Elements that are getting loaded during the run time must use event delegation in order to attach an event with it.

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