jQuery .parent() from an li:nth-child(xy)



我希望在这里找到帮助,我被困住了。

我使用这个函数在菜单中获取确切的活动 li 元素(带有第 n 个子元素):

function getElementPathWithJquery(element) {
    return $(element).parents().andSelf().map(function() {
        var $this = $(this);
        var entry = '';        
        if(this.nodeName === "BODY" || this.nodeName === "HTML") {
        // do nothing
        } else {
        entry += this.nodeName;
        if (this.className) entry += "." + this.className.replace(/ /g, '.');
        if (this.id) entry += "#" + this.id;
        if ($this.siblings(entry).length > 0) entry += ":nth-child(" + $this.prevAll(entry).length + ")";
        }
        return entry;
    }).get().join(" ");
}

现在,在请求的级别,父 li-element 应该得到一个 addClass('active') 属性,但以下内容不起作用:

if( $('#MENU_MAIN').find("ul.menu-level-3>li").hasClass('active')) {
var path = getElementPathWithJquery($('#MENU_MAIN').find("ul.menu-level-3>li.active"));
$(path).parent().parent().css('border','3px solid red');
}

我需要确切的第 n 个元素的原因是菜单系统是一个类别系统,一个条目实际上可以属于更多类别。 像这样的解决方案:

$('#MENU_MAIN').find("ul.menu-level-3>li.active").parent().parent().css('border','3px solid red');

有效,但根据找到的条目所属的类别数量,不止一个父级 li 可以有红色边框。

感谢您的帮助!问候罗伯特

您可以使用 parents() 来获取所有元素的祖先;您可以使用选择器来限制结果。

最新更新