如何获取使用ajax创建的表格单元格的值

时间:2015-03-23 09:49:40

标签: jquery ajax

我有一个像这样创建的DataTable:

table4 = $('#table').DataTable({
          ajax: "url.php"
          ...
         "columnDefs": [
                    {
                        "render": function (data, type, row) {
                            return '<center><button onclick="MyFunction();">myButton</button></center>';
                        },
                        "targets": 6
                    }
                ]
            });

这意味着第6列由按钮组成。 我想要做的是在MyFunction内输入按下按钮的同一行中第一个单元格(第0列)内的数据。我怎样才能获得这些信息?

4 个答案:

答案 0 :(得分:1)

尝试:

$('.button').click(function() {
    var value = $(this).closest('tr').find('td:first-child').text();
});

我更喜欢这样做,而不是指定onclick属性。否则你可以:

function MyFunction() {
    var value = $(this).closest('tr').find('td:first-child').text();
}

答案 1 :(得分:0)

而不是使用myfunction使用.on函数https://api.jquery.com/on/这可以处理页面重新插入后由javascript创建的元素。

$( "#table" ).on( "click", "button", function() { $(this).closest('tr').find('td').get(0); });

答案 2 :(得分:0)

看到你的按钮是动态创建的,所以你需要在args中传递this

return '<center><button class='myButton' onclick="MyFunction(this);">myButton</button></center>';

现在你的功能:

function MyFunction(elem){
    //the data inside the first cell (column 0)
    var tr = $(elem).closest('tr').find('td:eq(0)').text();
    console.log(tr);
}

或者我喜欢不引人注目的方式:

为按钮添加一个类名,并使用事件委托技术将事件绑定到DOM中动态创建的按钮元素:

$('#table').on('click', '.myButton', function(e){
    //the data inside the first cell (column 0)        
    var tr = $(this).closest('tr').find('td:eq(0)').text();
    console.log(tr);
});

在上面的代码段中,您可以将$('#table')替换为$(document), $(document.body) or $('body'),以将事件委派给静态父级。

答案 3 :(得分:0)

我最终做的是确保在将数据输出到数据表(url.php)的文件中回显我在第7位所需的内容,然后在它到达该行时:

"render": function (data, type, row) {

“data”参数已经包含我需要的数据。

相关问题