通过单击按钮获取表行的内容

我需要提取表中每一列的详细信息,例如“ Name/Nr”列。

  • 该表包含许多地址
  • 每行的最后一列有一个按钮,允许用户选择列出的地址。

问题: 我的代码只找到第一个具有 nr类的 <td>。我怎么才能让这个起作用?

下面是 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 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>
516797 次浏览

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.

Example here

Getting the full address using an array example here

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);
});

Example fiddle

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 .each method to iterate over them. For example:

$(".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 all of the td.nr elements 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 .closest method, like so:

$(".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
});
});
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()"

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
});

VIEW DEMO

Now let's focus on some frequently asked questions in such situations.

How to find the closest row?

Using .closest():

var $row = $(this).closest("tr");

Using .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().

var $row = $(this).parent()             // Moves up from <button> to <td>
.parent();            // Moves up from <td> to <tr>

Getting all table cell <td> values

So we have our $row and we would like to output table cell text:

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>
});

VIEW DEMO

Getting a specific <td> value

Similar to the previous one, however we can specify the index of the child <td> element.

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>
});

VIEW DEMO

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

Find element with id in row using jquery

$(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 );
});
});
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

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>john@example.com</td>
<td>click</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@example.com</td>
<td>click</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@example.com</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>

place folowing code in header section

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

define the table in body as

<table class="table table-hover">
<tr>
<th>Name/Nr.</th>
<th>Street</th>
<th>Town</th>
<th>Postcode</th>
<th>Country</th>
<th>View</th>
</tr>
            

<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="btn grabId" >View</button></td>
</tr>
            

</table>

then use this script

<script>
$(".grabId").click(function() {
var $row = $(this).closest("tr");    // Find the row
var $siteId = $row.find(".siteId").text(); // Find the text
alert($siteId);
});
</script>

Try this, just select javascript or jquery If you don't have header column, don't minus by 1

function rowClicked(element){
var rowJavascript = element.parentNode.parentNode;
var rowjQuery = $(element).closest("tr");
    

var rowIndexJavascript = rowJavascript.rowIndex-1;
var rowIndexjQuery = rowjQuery[0].rowIndex-1;
    

console.log("rowIndexJavascript : ",rowIndexJavascript);
console.log("rowIndexjQuery : ",rowIndexjQuery);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Row ID</th>
<th>Button</th>
</tr>
<tr>
<td>0</td><td><button type="button"  onclick="rowClicked(this)">test1</button></td>
</tr>
<tr>
<td>1</td><td><button type="button" onclick="rowClicked(this)">test2</button></td>
</tr>
<tr>
<td>2</td><td><button type="button" onclick="rowClicked(this)">test3</button></td>
</tr>
</table>