如何获取点击的表格行的值?

Ram*_*ing -1 html javascript jquery html-table

我的问题是:如何获取单击的行和列的值?

我的代码是这样的:

JS:

$.ajax({
        type: 'POST',
        url: url,
        data: json,
        success: function(data) {
            var response_array = JSON.parse(data);
            var columns = ['id', 'name', 'email', 'telephone', 'website', 'city'];
            var table_html = ' <tr>\n' +
                '<th id="id">Id</th>\n' +
                '<th id="name">Bedrijfnaam</th>\n' +
                '<th id="email">E-mail</th>\n' +
                '<th id="telephone">Telefoon</th>\n' +
                '<th id="website">Website</th>\n' +
                '<th id="city">Plaats</th>\n' +
                '</tr>';
            for (var i = 0; i < response_array.length; i++) {
                //create html table row
                table_html += '<tr>';
                for (var j = 0; j < columns.length; j++) {
                    //create html table cell, add class to cells to identify columns
                    table_html += '<td class="' + columns[j] + '" >' + response_array[i][columns[j]] + '</td>'
                }
                table_html += '</tr>'
            };
            $("#posts").append(table_html);
        },
        error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
    });
Run Code Online (Sandbox Code Playgroud)

这是 HTML:

<div class="tabel">
     <table id="posts">
     </table>
</div>
Run Code Online (Sandbox Code Playgroud)

我已经尝试过以下方法:

 $('#posts').click(function(){
        console.log("clicked");
        var id = $("tr").find(".id").html();
        console.log(id);
});
Run Code Online (Sandbox Code Playgroud)

遗憾的是,无论我点击哪里,这只会给我第一行的 id。

任何帮助表示赞赏!

拉蒙

lpr*_*hap 7

下面的方法应该可以找到ID

$('#post').on('click', function(e){
var id = $(e.target).closest('tr').find(".id").html();
console.log(id)
})
Run Code Online (Sandbox Code Playgroud)