与jQuery的.Closest相反(顶部/顶部?) [英] Opposite to jQuery's .Closest (Top/Far-Most?)

查看:191
本文介绍了与jQuery的.Closest相反(顶部/顶部?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有很多子菜单的代码,这些子菜单共享相同的类名.

I have a code with lots of submenus that share the same class name.

这是一个结构:

.menu
  .sub-menu
  .sub-menu
    .sub-menu
    .sub-menu
  .sub-menu
    .sub-menu
      .elem
      .elem
  .sub-menu

请注意,.sub-menu可能有无限深.

Note that .sub-menu may be infinite levels deep.

那么我该如何实现:单击.elem时,我想向上遍历DOM,直到到达最顶部的.sub-menu并对其应用样式.我知道.closest().parent().find(),但是我不知道jQuery是否具有诸如.topMost(selector)这样的功能?

So how do I achieve this: when .elem is clicked, I want to travers the DOM upwards until the top-most .sub-menu is reached and apply a style to it. I am aware of .closest() and .parent() and .find(), but I have no idea if jQuery has such feature such as .topMost(selector)?

我能想到的唯一方法可能是运行循环并遍历新元素的.closest('.sub-menu'),直到其长度为零(此类的父级不再存在,因此它必须是最顶层的).但是,我认为应该有一种更实际的方法.

The only way I can think of is maybe running a loop and going through .closest('.sub-menu') of the new element until its length is zero (there are no more parents with this class, so it must be the top-most). However, I think there should be a more practical approach to this.

推荐答案

假设最接近的对面"是您想要最远"的父元素,则可以使用parents().last(),如下所示:

Assuming by 'opposite of closest' you want the 'furthest' parent element, you can use parents().last(), like this:

$('.elem').click(function() {
    var $topSubMenu = $(this).parents('.sub-menu').last();
});

请注意,当jQuery遍历DOM时,您需要数组中的最后一个元素,因此顶级项将是集合中的最后一个元素.

Note, you want the last element in the array as jQuery traverses up the DOM, so the top-level item will the final one in the collection.

这篇关于与jQuery的.Closest相反(顶部/顶部?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆