【问题标题】:Find an element's sibling in a list of elements在元素列表中查找元素的兄弟
【发布时间】:2011-04-05 19:48:30
【问题描述】:

好的,这就是我得到的:

我有一个缓存在变量中的元素列表:

elementList = $(".list-of-elements-with-this-class");

我还有一个从该列表中动态生成的元素缓存在另一个变量中:

elementList.click(
    function()
    {
        cachedItem = $(this);
    }
);

我要做的是在 elementList 中找到 cachedItem,然后在列表中选择 cachedItem 的上一个或下一个兄弟。

所以伪代码应该是这样的:

nextCachedItem = elementList.find(cachedItem).next();

prevCachedItem = elementList.find(cachedItem).prev();

显然,上述方法行不通。 :-)

提前感谢您的帮助!

-蒂姆。

【问题讨论】:

  • This 可能会有所帮助。

标签: jquery list select jquery-selectors selection


【解决方案1】:

我相信 next()prev() 处理 DOM 元素,而不是查询返回的 jQuery 节点列表。因此,您必须手动处理 jQuery 对象中节点列表的索引。

试试:

// RAW DOM Nodes
elementList.get(elementList.index(cachedItem) - 1); // previous
elementList.get(elementList.index(cachedItem) + 1); // next

或者:

// jQuery Objects/Node list
elementList.eq(elementList.index(cachedItem) - 1); // previous
elementList.eq(elementList.index(cachedItem) + 1); // next

【讨论】:

  • 太棒了!但是,上述内容不断返回构成 elementList 的锚标记的 href 属性。
  • @scullytr:这可能与您尝试使用它的方式有关……您想对上述操作的结果做什么?例如,如果您只是尝试将其放入警报中,那么这是预期的行为,因为它将使用作为 HREF 值的字符串表示。
  • 我想向生成的兄弟节点及其父节点添加一个类
  • 请记住,这是未包含在 jQuery 对象中的原始 DOM 节点/元素。如果您希望它包含在 jQuery 中,我仍然相信 eq 会比 get 更适合您。
  • 完美!做到了!非常感谢! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
  • 2015-08-27
  • 2014-07-16
  • 2020-11-15
  • 1970-01-01
相关资源
最近更新 更多