练习的目的是找到包含信息的行。当我们到达那里时,我们可以轻松提取所需的信息。
回答
$(".use-address").click(function() { var $item = $(this).closest("tr") // Finds the closest row <tr> .find(".nr") // Gets a descendent with .text(); // Retrieves the text within <td> $("#resultas").append($item); // Outputs the answer});现在,让我们集中讨论这种情况下的一些常见问题。
如何找到最接近的行?
使用.closest()
:
var $row = $(this).closest("tr");使用.parent()
:
您也可以使用
.parent()方法将DOM树向上移动。这只是有时与
.prev()和一起使用的替代方法
.next()。
var $row = $(this).parent() // Moves up from <button> to <td> .parent(); // Moves up from <td> to <tr>
获取所有表单元格<td>
值
因此,我们有我们
$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>});获得特定<td>
值
与上一个相似,但是我们可以指定子
<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>});有用的方法
.closest()
-获取与选择器匹配的第一个元素.parent()
-获取当前匹配元素集中每个元素的父元素.parents()
-获取当前匹配元素集中每个元素的祖先.children()
-获取匹配元素集中每个元素的子元素.siblings()
-获取匹配元素集中每个元素的同级.find()
-获取当前匹配元素集中每个元素的后代.next()
-获得匹配元素集中每个元素的紧随其后的同级.prev()
-获取匹配元素集中每个元素的前一个同级



