【发布时间】:2012-06-01 19:17:25
【问题描述】:
我希望在这里找到帮助,我被卡住了。
我使用这个函数来获取菜单中确切的活动 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 可能有红色边框。
感谢您的帮助! 问候, 罗伯特
【问题讨论】:
-
我应该澄清一下:路径找到正确,但附加到 $(path) 的 .parent().parent() 链不会产生任何结果...
-
您为什么要尝试从您刚刚使用 CSS 选择器解析的元素中解码 CSS 选择器?
-
是的,我昨天晚上意识到这很愚蠢......嗯......但是我怎样才能把它从这里放回 CSS 选择器,然后像 SELECTED_AGAIN.parent( ).parent().css(doSomthing)?
标签: jquery parent css-selectors