I am trying to 开发者_运维问答build a menu in jquery with a hover and selected state...
On hover image is replaced with highlighted version and I also need a selected state for when I click a menu item (image replaced to a selected version).
The problem I have is when I click the another menu item I want to turn off any other selected menu items and return them to their original src before selecting the new menu item.
Here is my attempt... :\
$("#profile_menu ul li").click(function(){
$(this).addClass("menu_selected")
var img = $(this).children().children(".menu_icon").attr("src")
var allimgs = $(".menu_icon").attr("src")
var selected_state = img.replace(".png","_click.png")
var normalstate = allimgs.replace("_click.png",".png")
$(".menu_icon").attr("src",normal_state)
$(this).children().children(".menu_icon").attr("src",selected_state)
})
The problem is when I click the next item it changes all of the menu images to the same image...
Thanks in advance,
Chris
This
$(".menu_icon").attr("src")
will get the image URL of the first matched element. You are then setting this URL for all other images, making all the images the same.
Better: Set the new attribute by passing a function to .attr()
:
$(".menu_icon").attr("src", function(i, src) {
return src.replace("_click.png",".png");
});
You can do this for the selected image too, which would result in this code:
$("#profile_menu ul li").click(function() {
$(this)
.addClass("menu_selected")
.find('.menu_icon').attr('src', function(i, src) {
return src.replace(".png","_click.png");
});
$(".menu_icon").attr("src", function(i, src) {
return src.replace("_click.png",".png");
});
// you might also need
$(this).siblings().removeClass('menu_selected');
});
Don't forget semicolons ;
at the end a statement!
精彩评论