简体   繁体   English

jQuery DOM遍历

[英]jQuery DOM Traversal

I'm having trouble finding the easiest path to an item using jQuery (although the solution doesn't have to necessarily use jQuery, it's just available as a tool).我很难找到使用 jQuery 的项目的最简单路径(尽管解决方案不一定必须使用 jQuery,它只是作为工具提供)。 Here is a simplified code sample:这是一个简化的代码示例:

<tr>
    <td>Bob Jones</td>
    <td class="class-name">
        <a href="/start/1">Workshop</a>
    </td>
    <td>06/04/11</td>
    <td class="last">
         <a href="#" class="button">Delete</a>
    </td>
</tr>

I'm looking to get the word "Workshop" when the "Delete" link is clicked, and I'm wondering which is the most efficient means of doing so.单击“删除”链接时,我希望获得“研讨会”一词,我想知道哪种方法最有效。 Would it be to a) go one level up the tree to the <td> element and find the sibling element by class name, then the link/text value inside... b) to go up to the <tr> level and search for the class-name, etc. or c) do something I hadn't considered.会不会是 a) go 在树的上一级到<td>元素,并通过 class 名称找到兄弟元素,然后是里面的链接/文本值... b) 到 Z34D1F91FB2E514B8576FAB1A75A8 级别到 <td <tr>对于类名等或 c) 做一些我没有考虑过的事情。

I always seem to have trouble with understanding when and how to do dom traversal in javascript or jquery and wanted to know the why's behind different methods available, and whether it matters how you get to the end result.我似乎总是难以理解何时以及如何在 javascript 或 jquery 中进行 dom 遍历,并且想知道不同方法背后的原因,以及如何获得最终结果是否重要。

This simple schema is often the best:这个简单的模式通常是最好的:

  1. Say in plain English what you want to find.用简单的英语说出你想找到的东西。
  2. Treat the result as pseudo-code.将结果视为伪代码。
  3. Literally translate it to code.从字面上将其翻译为代码。

In your case, it's probably:在你的情况下,它可能是:

I need <td class="class-name"> on the row to which the clicked element belongs.

This translates directly to your b) option:这直接转化为您的b)选项:

$(this).closest("tr").find("td.class-name")
$("td.class-name a", $(this).closest("tr")).text())

$(this).closest("tr").children(":nth-child(2)").children("a").text()

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM