【问题标题】:how to get the value of the clicked table row?如何获取点击的表格行的值?
【发布时间】:2017-09-11 17:58:48
【问题描述】:

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

我的代码是这样的:

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); }
    });

这是 HTML:

<div class="tabel">
     <table id="posts">
     </table>
</div>

我尝试了以下方法:

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

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

感谢任何帮助!

拉蒙

【问题讨论】:

  • 继续阅读如何在 jQuery 中使用 $(this) ...
  • 我试过 $(this) 如果这就是你的意思,但结果相同

标签: javascript jquery html html-table


【解决方案1】:

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

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

【讨论】:

  • 谢谢,成功了!我会接受这个答案
【解决方案2】:

点击行的 HTML 内容

 $('#posts tr').click(function(){
       $(this).html();
 });

点击 td 的文本

 $('#posts tr td').click(function(){
        $(this).text();
 });

如果您使用 ajax 并且您正在重绘元素,您将无法通过点击功能捕获它们。您将需要添加功能:

$(document).on('click','#posts tr td','function(){
      $(this).text();
});

【讨论】:

  • 好像没用,不过谢谢你的建议!
【解决方案3】:

您可以尝试为您的表使用 AddEventListener,它肯定会起作用。 像这样:

let posts = document.getlementById('posts');
posts.addEventListener('click',(e) => {
// anything you need here, for example:
console.log(e.target);
e.preventDefault();
});

同样——不要对网格中的元素使用相同的 ID(如您拥有的 id="id"),它应该是不同的。

【讨论】:

  • 为什么在这种情况下我对元素使用相同的 id 时这很重要?有了选择器,我无论如何都会得到唯一的 ID 对吗?
  • 是的,Ramon,对于您的问题,这并不重要——这只是一个通知。但根据问题 - 使用事件侦听器允许您“侦听”所需的 DOM 事件,无论它来自哪里 - ajax 或初始 DOM 加载
  • 好的,那我明白了:)
  • 希望对你有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 2016-04-18
  • 2020-12-18
  • 1970-01-01
相关资源
最近更新 更多