2012-11-22 23 views
1

我想使用我之前定義的menuBar對象對其中的對象進行操作。重複使用變量而不是新的DOM搜索

var menuBar = $(".menu-bar ul"); 
var menuActive = menuBar.find("li.active"); 
menuBar.hover(function(){ 
    menuActive.toggleClass("active"); 
}); 
$('.menu-bar ul > li > a[href="'+ window.location.href +'"]').parent().addClass("active"); 

我不喜歡的是再次調用DOM搜索來定義父鏈接的活動類。

有關如何使用menuBar變量做到這一點的任何想法?

+0

所以,你不想調用'.parent()'? – Musa

回答

1

嘗試這樣的事情

var menuBar = $(".menu-bar ul"); 
var menuActive = menuBar.find("li.active"); 
menuBar.hover(function(){ 
    menuActive.toggleClass("active"); 
}); 
$('li > a[href="'+ window.location.href +'"]',menuBar).parent().addClass("active"); 
1

您可以指定一個上下文中搜索:

$('li > a[href="'+ window.location.href +'"]', menuBar.children()).parent().addClass("active"); 

這裏menuBar.children()將是背景。

3

你可能在尋找:

menuBar.find('> li > a[href="'+ window.location.href +'"]').parent().addClass("active"); 

還是真的,因爲你要選擇父:

menuBar.find('> li:has(> a[href="'+ window.location.href +'"])').addClass("active"); 

:has僞類允許您選擇其中包含的元素另一個元素。這真的是你要做的,你應該允許選擇器本身做任何優化。

+0

我真的很喜歡這個方法!感謝彌敦道,不是尋找的粉絲 –

相關問題