I have a situation where I need to identify if a list element (li) has a sub (ul) underneath it, and if it does, I need to change the background image of the anchor tag (a) under the (li) to display a sub-menu indicator image (say subMenuImg.gif). All the anchor tags (a) have a css class of "menuLink", if there is a sub-menu for that list element (li), I would like to change it to subMe开发者_Go百科nuLink. I can then apply the styles on this sub-menu link as needed.
How can I best do it with jQuery?
You could get a list of li with ul underneath it with:
$("li:has(ul)")
Then you can apply a different style to each immediate child of the li with
$(this).find(">a").addClass("hasSubmenu");
Put it all together like this.
$("li:has(ul)").each(function(){
$(this).find(">a").addClass("hasSubmenu");
});
I'm not sure what you mean by "dynamically", but adding a class to a link is easy.
$('li').addClass('menuLink');
Although the real question is how you're going to be handling everything else, and without more information, I can't begin to elaborate on that.
//loop ul that is a direct children of an li
$("li").children("ul").each(function(){
//find the a of the parent (in this case the parent is li) since $(this) refers to the ul
$(this).parent().find("a")
//change the background image of the said "a"
.css("background-image","subMenuImg.gif");
//remove the class of the "a" and add a new class
.removeClass("menuLink").addClass("subMenuLink")
});
Hope that helps. I'm just wondering why you have to add the background image manually when you can just let's say
.menuLink{}
.subMenuLink{ background-image:url('subMenuImg.gif'); }
精彩评论