[英]How to get selected row from a table in html using javascript?
I have a html table and a button below it, I want to get the data from the selected row whenever that button is clicked.我有一个 html 表和一个按钮,我想在单击该按钮时从所选行中获取数据。 How shall I go about it?我该怎么办?
If I understand what you mean, you want a user to be able to select a row out of a table by clicking on it.如果我理解您的意思,您希望用户能够通过单击从表中选择一行。 Then when they click the button, you can capture the selected row's data in each cell.然后当他们单击按钮时,您可以在每个单元格中捕获所选行的数据。
I'll use JQuery in the explanation.我将在解释中使用 JQuery。
You will want to create an event handler for a click event on a <tr>
.您需要为<tr>
上的点击事件创建一个事件处理程序。 When that <tr>
is clicked, you can apply a CSS class such as .selected
to it.当那个<tr>
被点击时,你可以应用一个 CSS 类,比如.selected
到它。 Then when the user clicks the button, you have another event handler loop through the .selected
class's children and return the values (which would be <td>
's).然后,当用户单击按钮时,您有另一个事件处理程序循环遍历.selected
类的子项并返回值(将是<td>
的)。
$('tr').click(function() {
$('.selected').removeClass('selected');
$(this).addClass('selected');
});
$('#submit').click(function() {
$('.selected').children().each(function() {
alert($(this).html());
});
});
Here is a working example on JSFiddle using JQuery.这是一个使用 JQuery 的关于 JSFiddle的工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.