更新时间:2023-12-04 11:39:34
练习的目的是找到行包含信息。当我们到达那里时,我们可以轻松提取所需的信息。
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.
$(".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.
使用 .closest()
:
Using .closest()
:
var $row = $(this).closest("tr");
使用 .parent()
:
Using .parent()
:
您还可以使用 .parent()
方法。这只是一种替代方法,有时与 .prev()
和 .next()
一起使用。
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>
< td>
值 所以我们有 $ row
,我们想输出表格单元格text:
<td>
valuesSo 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
与前一个类似,但是我们可以指定孩子的索引< td>
元素。
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
.closest()
- 获取与选择器匹配的第一个元素 .parent()
- 获取当前匹配元素集中每个元素的父元素 .parents()
- 获取当前每个元素的祖先匹配元素集 .children()
- 获取匹配元素集中每个元素的子元素 .siblings()
- 获取该组中每个元素的兄弟姐妹匹配元素 .find()
- 获取当前匹配元素集中每个元素的后代 .next()
- 获取匹配元素集中每个元素的紧随其后的兄弟 .prev()
- 获取匹配元素集中每个元素的前一个兄弟.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