Javascript 单击按钮获取表格行的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14460421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the contents of a table row with a button click
提问by chuckfinley
I need to extract the details of each column in my table. For example, column "Name/Nr.".
我需要提取表中每一列的详细信息。例如,列“名称/编号”。
- The table contains a number of addresses
- The very last column of each row has a button that lets a user choose a listed address.
- 该表包含多个地址
- 每行的最后一列都有一个按钮,让用户可以选择列出的地址。
Problem:My code only picks up the first <td>that has a class nr. How do I get this to work?
问题:我的代码只选择第一个<td>有 class 的nr。我如何让这个工作?
Here's the jQuery bit:
这是 jQuery 位:
$(".use-address").click(function() {
var id = $("#choose-address-table").find(".nr:first").text();
$("#resultas").append(id); // Testing: append the contents of the td to a div
});
Table:
桌子:
<table id="choose-address-table" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Nr.</th>
<th>Street</th>
<th>Town</th>
<th>Postcode</th>
<th>Country</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td class="nr"><span>50</span>
</td>
<td>Some Street 1</td>
<td>Leeds</td>
<td>L0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" />
</td>
</tr>
<tr>
<td class="nr">49</td>
<td>Some Street 2</td>
<td>Lancaster</td>
<td>L0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" />
</td>
</tr>
</tbody>
</table>
回答by martynas
The object of the exercise is to find the row that contains the information. When we get there, we can easily extract the required information.
练习的目的是找到包含信息的行。当我们到达那里时,我们可以轻松地提取所需的信息。
Answer
回答
$(".use-address").click(function() {
var $item = $(this).closest("tr") // Finds the closest row <tr>
.find(".nr") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$("#resultas").append($item); // Outputs the answer
});
Now let's focus on some frequently asked questions in such situations.
现在让我们集中讨论在这种情况下的一些常见问题。
How to find the closest row?
如何找到最近的行?
Using .closest():
使用.closest():
var $row = $(this).closest("tr");
Using .parent():
使用.parent():
You can also move up the DOM tree using .parent()method. This is just an alternative that is sometimes used together with .prev()and .next().
您还可以使用.parent()方法向上移动 DOM 树。这只是有时与.prev()和一起使用的替代方法.next()。
var $row = $(this).parent() // Moves up from <button> to <td>
.parent(); // Moves up from <td> to <tr>
Getting all table cell <td>values
获取所有表格单元格<td>值
So we have our $rowand we would like to output table cell text:
所以我们有我们的$row,我们想输出表格单元格文本:
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td"); // Finds all children <td> elements
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
Getting a specific <td>value
获取特定<td>值
Similar to the previous one, however we can specify the index of the child <td>element.
与前一个类似,但是我们可以指定子<td>元素的索引。
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
Useful methods
有用的方法
.closest()- get the first element that matches the selector.parent()- get the parent of each element in the current set of matched elements.parents()- get the ancestors of each element in the current set of matched elements.children()- get the children of each element in the set of matched elements.siblings()- get the siblings of each element in the set of matched elements.find()- get the descendants of each element in the current set of matched elements.next()- get the immediately following sibling of each element in the set of matched elements.prev()- get the immediately preceding sibling of each element in the set of matched elements
.closest()- 获取与选择器匹配的第一个元素.parent()- 获取当前匹配元素集合中每个元素的父元素.parents()- 获取当前匹配元素集合中每个元素的祖先.children()- 获取匹配元素集中每个元素的子元素.siblings()- 获取匹配元素集中每个元素的兄弟.find()- 获取当前匹配元素集中每个元素的后代.next()- 获取匹配元素集中每个元素的紧随其后的兄弟元素.prev()- 获取匹配元素集中每个元素的前一个兄弟元素
回答by Manse
Try this:
尝试这个:
$(".use-address").click(function() {
$(this).closest('tr').find('td').each(function() {
var textval = $(this).text(); // this will be the text of each <td>
});
});
This will find the closest tr(going up through the DOM) of the currently clicked button and then loop each td- you might want to create a string / array with the values.
这将找到最接近的tr(通过 DOM 向上)当前单击的按钮,然后循环每个td- 您可能想要创建一个带有值的字符串/数组。
回答by Rory McCrossan
You need to change your code to find the row relative to the button which was clicked. Try this:
您需要更改代码以查找与单击的按钮相关的行。尝试这个:
$(".use-address").click(function() {
var id = $(this).closest("tr").find(".nr").text();
$("#resultas").append(id);
});
回答by cody collicott
function useAdress () {
var id = $("#choose-address-table").find(".nr:first").text();
alert (id);
$("#resultas").append(id); // Testing: append the contents of the td to a div
};
then on your button:
然后在你的按钮上:
onclick="useAdress()"
回答by dgvid
The selector ".nr:first"is specifically looking for the first, and only the first, element having class "nr"within the selected table element. If you instead call .find(".nr")you will get all of the elements within the table having class "nr". Once you have all of those elements, you could use the .eachmethod to iterate over them. For example:
选择器".nr:first"专门寻找第一个,也是唯一一个"nr"在所选表格元素中具有类的元素。如果您改为调用,.find(".nr")您将获得表中具有 class 的所有元素"nr"。一旦你拥有了所有这些元素,你就可以使用.each方法来迭代它们。例如:
$(".use-address").click(function() {
$("#choose-address-table").find(".nr").each(function(i, nrElt) {
var id = nrElt.text();
$("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
});
});
However, that would get you allof the td.nrelements in the table, not just the one in the row that was clicked. To further limit your selection to the row containing the clicked button, use the .closestmethod, like so:
但是,这将使您获得表格中的所有td.nr元素,而不仅仅是单击的行中的元素。要将您的选择进一步限制为包含单击按钮的行,请使用.closest方法,如下所示:
$(".use-address").click(function() {
$(this).closest("tr").find(".nr").each(function(i, nrElt) {
var id = nrElt.text();
$("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
});
});
回答by Super Model
Find element with id in row using jquery
使用jquery在行中查找带有id的元素
$(document).ready(function () {
$("button").click(function() {
//find content of different elements inside a row.
var nameTxt = $(this).closest('tr').find('.name').text();
var emailTxt = $(this).closest('tr').find('.email').text();
//assign above variables text1,text2 values to other elements.
$("#name").val( nameTxt );
$("#email").val( emailTxt );
});
});
回答by Muhammad Waqas Aziz
var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
$(this).find("td").each(function () {
values[count] = $(this).text();
count++;
});
});
Now values array contain all the cell values of that row can be used like values[0] first cell value of clicked row
现在 values 数组包含该行的所有单元格值,可以像 values[0] 单击行的第一个单元格值一样使用
回答by ankush
Here is the complete code for simple example of delegate
这是委托的简单示例的完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Striped Rows</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>[email protected]</td>
<td>click</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>[email protected]</td>
<td>click</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>[email protected]</td>
<td>click</td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function(){
$("div").delegate("table tbody tr td:nth-child(4)", "click", function(){
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(2)");
$.each($tds, function() {
console.log($(this).text());
var x = $(this).text();
alert(x);
});
});
});
</script>
</div>
</body>
</html>

