[英]Using jQuery to select row from table
I have a HTML table as outlined below (with sample data):我有一个 HTML 表,如下所示(带有示例数据):
<table class="tbl">
<caption>Version History Table</caption>
<thead>
<tr>
<th>Change Date</th>
<th>Change Type</th>
<th>Description</th>
<th>StaffID</th>
</tr>
</thead>
<tbody>
<tr>
<td>16/04/2010 07:30</td>
<td>Edit</td>
<td>New role</td>
<td>00215</td>
</tr>
<tr>
<td>15/02/2012 14:37</td>
<td>Edit</td>
<td>Out of stock</td>
<td>85487</td>
</tr>
<tr>
<td>14/03/2013 10:18</td>
<td>Add</td>
<td>Out of date</td>
<td>15748</td>
</tr>
</tbody>
</table>
What I am trying to achieve is when a user selects a row a pop-up/dialog box appears showing details of the history.我想要实现的是,当用户选择一行时,会出现一个弹出/对话框,显示历史记录的详细信息。
Try this试试这个
$('tr', 'table.tbl tbody').click(function(){
alert($(this).text());
});
Edit:- Based on your comment, you dont need to put onClick in all trs.编辑:- 根据您的评论,您不需要在所有 trs 中都放置 onClick。 you can use Jquery selectors to assign click event to all your trs
您可以使用 Jquery 选择器将点击事件分配给您的所有 trs
With your showDialog method you can do this and inside showDIalog , this will be the clicked tr
.使用您的 showDialog 方法,您可以执行此操作,并且在 showDIAlog 中,这将是单击的
tr
。
$('tr', 'table.tbl tbody').click(showDialog);
If you construct the table using, for example, a tag like p or something else to identify a column that's a key on your context例如,如果您使用诸如p 之类的标记或其他标记来构建表,以标识作为上下文键的列
<table class="tbl">
<caption>Version History Table</caption>
<thead>
<tr>
<th>Change Date</th>
<th>Change Type</th>
<th>Description</th>
<th>StaffID</th>
</tr>
</thead>
<tbody>
<tr>
<td>16/04/2010 07:30</td>
<td>Edit</td>
<td>New role</td>
<td><p>00215</p></td>
</tr>
<tr>
<td>15/02/2012 14:37</td>
<td>Edit</td>
<td>Out of stock</td>
<td><p>85487</p></td>
</tr>
<tr>
<td>14/03/2013 10:18</td>
<td>Add</td>
<td>Out of date</td>
<td><p>15748</p></td>
</tr>
</tbody>
</table>
<p>Picked row:</p>
<p id="linea"></p>
<p>The key for the row picked (StaffID) was:</p>
<p id="StaffID"></p>
You can extract the key of the choosen row also using this script:您也可以使用此脚本提取所选行的键:
$(document).ready(function(){
$('table tbody tr').click(function(){
$("#linea").text($(this).text())
$("#StaffID").text($(this).children('td').children('p').text())
});
});
The below code will show the details as mentioned in the question.下面的代码将显示问题中提到的详细信息。
<script>
$(document).ready(function () {
$('.tbl tbody tr').click(function () {
var details = '';
details += 'Change Date : ' + $(this).find('td:first-child').html() + '\n';
details += 'Change Type : ' + $(this).find('td:nth-child(2)').html() + '\n';
details += 'Description : ' + $(this).find('td:nth-child(3)').html() + '\n';
details += 'StaffID : ' + $(this).find('td:nth-child(4)').html() + '\n';
alert(details);
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.