Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

jQuery - change the CSS of the menu item's path in the dynamically created menu

I'm using that jQuery Vertical Menu Library www.dynamicdrive.com/dynamicindex1/ddsmoothmenu.htm I want to accomplish the selection of the selected path. Let's say that I go through that menu (in the demo on that site above) by the path:

Folder 2 > Folder 2.1 > Folder 3.1.1 > SubItem 3.1.1.1

When I click on the SubItem 3.1.1.1 I want that the all previous items (from the path above) changes their backgrounds. The code below selects only the top-most item. How to fix that ?

    $('#nav > li').click(function () {
        $(this).children('a').css('background-color', 'red'); 
        $(this).parents('ul').each(function () { $(this).prev('a').css('background-color', 'red'); });
    });

. In that scenario, my code fails.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way the menu seems to be organized, the click event will bubble up from child li to parent li, so you just need to bind the click event to all menu items and set the background for the current element:

$('#nav li').click(function () {
    $(this).children('a').css('background-color', 'red'); 
});

You still might like to unset the red background when you click on another menu item


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...