首页 > 解决方案 > 如何从动态填充的表格中获取可点击单元格的数据

问题描述

我有一个动态填充的表。我需要在单击时获取单元格的数据。如何做到这一点。

我正在以下列方式填充表格:-

 function fetchAllRecords() {
    $('#tab_logic').empty();
    var html="";
    html+="<thead> <tr>  <th scope='col'>Order Id</th> <th scope='col'>Latitude/Longitude</th> <th scope='col'>OTP</th> <th scope='col'>Call Status</th> <th scope='col'>Call Duration</th> <th scope='col'>Call Unit</th> </tr> </thead> <tbody> ";
    for (var i = 1; i <= 6; i++) {
      html+="<tr> <td onclick='tableFunction()'> <p id='trow"+i+"'> Data</p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td></tr>"
    }
    html+="</tbody>";
    $('#tab_logic').append(html);

    }

我尝试获取这样的数据,但没有奏效

function tableFunction(){
    var txt = $(this).text();
    alert(txt);

    }

标签: jqueryhtml

解决方案


您需要this作为参数传递给函数。

      html+="<tr> <td onclick='tableFunction(this)'> <p id='trow"+i+"'> Data</p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td></tr>"

然后使用函数参数

function tableFunction(element) {
    var txt = element.innerText;
    alert(txt);
}

但我建议您在 jQuery 中使用事件委托,而不是使用内联 JavaScript。请参阅动态创建的元素上的事件绑定?


推荐阅读