这是我的 html 表格
<table>
<thead>
<tr>
<td class="td20"><h3>Patient Name</h3></td>
<td class="td20"><h3>Summary</h3></td>
<td class="td20"> <h3>Created</h3></td>
<td class="td20"><h3>Last visit</h3></td>
<td class="td20"> <h3>Refer to a Doctor</h3></td>
</tr>
</thead>
<tbody id="patient_table">
<tr id="1">
<td class="td20">Patient Name</td>
<td class="td20">Summary</td>
<td class="td20">Created</td>
<td class="td20">Last visit</td>
<td class="td20">Refer to a Doctor</td>
</tr>
<tr id="2">
<td class="td20">Patient Name</td>
<td class="td20">Summary</td>
<td class="td20">Created</td>
<td class="td20">Last visit</td>
<td class="td20">Refer to a Doctor</td>
</tr>
</tbody>
</table>
这是我的脚本:
$("#patient_table").click(function(e) {
var id = $(this).children('tr').attr('id');
alert(id);
});
<tr>
在 <tbody>
内动态生成。
我需要找到id
的<tr>
点击<tr>
本身。
通过脚本,我总是得到第一个 <tr>
id
仅不管第二个 <tr>
点击。
最佳答案
改用这个:
$("#patient_table").on('click','td',function (e) {
var id = $(this).closest('tr').attr('id');
alert(id);
});
<强> jsFiddle example
既然您提到了动态生成的行,您希望使用 .on()
将事件处理委托(delegate)给表格单元格。
关于javascript - 如何从tbody jquery中找到点击的tr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17150741/