jquery - 如何从动态填充的表格中获取可点击单元格的数据
问题描述
我有一个动态填充的表。我需要在单击时获取单元格的数据。如何做到这一点。
我正在以下列方式填充表格:-
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);
}
解决方案
您需要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。请参阅动态创建的元素上的事件绑定?
推荐阅读
- android - Android:在 ViewFlipper 内的按钮上执行单击()?
- python - 字符串连接布尔值两次返回 True
- python - mysql循环查询平均python
- rust - 弧
> 内部闭包:期望一个实现了 `Fn` 特性的闭包,但这个闭包只实现了 `FnOnce` - javascript - parseFloat 将数千变成个位数 - 出乎意料
- python - 如何在 django 中跟踪用户的每月订阅使用情况?
- amazon-web-services - 使用 LWA 的 Alexa BDD 测试的 Authcode
- node.js - Google Cloud Storage - 尝试删除存在的对象时找不到
- javascript - useEffect 中的异步 useState 覆盖状态值
- python - 根据条件迭代熊猫列