0

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

我使用此函数在菜单中获取确切的活动 li 元素(使用 nth-child):

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 元素将获得一个 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 可能有红色边框。

谢谢你的帮助!问候,罗伯特

4

1 回答 1

1

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

于 2012-05-28T08:51:29.197 回答