【问题标题】:jQuery - Select previous DOM element matching a class, when the DOM element is not in the same treejQuery - 当 DOM 元素不在同一棵树中时,选择与某个类匹配的前一个 DOM 元素
【发布时间】:2011-04-07 01:22:21
【问题描述】:

我正在尝试使用 jQuery 从我开始使用的 DOM 对象访问代码中较早出现的 DOM 对象。使用 jQuery 的遍历方法,如 .parentsUntil,这通常很容易。但是,在这种情况下,我要查找的对象不是我开始的对象的父对象或兄弟对象。

例如,想象一下这个层次结构:

    • tr
      • td A
      • td B
    • tr
      • td C
        • 输入D

从输入 D 开始,当 A 和 D 之间可能有任意数量的元素时,是否可以找到 td A 的 html()?

感谢您的帮助,如果这太含糊,我深表歉意,如果需要,我会重写问题。

【问题讨论】:

  • 我假设 A B C 和 D 不是 ID,所以你不能简单地直接选择 A。他们是班级吗?纯文本内容?有多个As的麻烦吗?多个表?
  • 正确,A B C 和 D 不是 ID。问题是输入 D,很容易输入 Z,我正在寻找 HTML 中第一次出现在它之前的类。输入 Z 和 td A 在 DOM 树中可能没有关系。

标签: jquery dom css-selectors


【解决方案1】:

我不确定您在问什么(请参阅我上面的评论)。因此,假设您想在 DOM 中找到最接近元素 DtdA 的 html 内容,同时也在“上方”D,您可以尝试这样的操作:

$('input#D')      // somehow uniquely identify our starting point
  .closest('tr')  // up to the closest enclosing TR
  .prevAll()      // and then get its preceding siblings
  .has('td.B')    // reduce this set to only those containing a td.B
  .last()         // choose the last one (thus closest to 'D')
  .find('td.B')   // now work downward to td.B itself
  .html();        // and get the content

这不是我的想法,所以可能有一种更有效的方法来做到这一点(并且未经测试),但也许这会给你一些想法。

【讨论】:

  • 谢谢肯!我认为这适用于这种情况。你摇滚!
猜你喜欢
  • 2014-09-30
  • 2021-09-20
  • 2014-09-23
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多