简体   繁体   中英

Javascript sessionStorage make last selected item the first item when image link is clicked

I have this JS Code that expands the last opened item on my menu when the page is changed, if an image at the top of the page is clicked to go to the homepage how can i make the 'Home' link on the menu be the last active clicked link?

<script>
$(document).ready(function(){
    //Loop through nav items, compare to expanded item ID from sessionStorage so we can expand whichever item was previously expanded
    if(sessionStorage.getItem("activeMenuItemID") != undefined){
        $("#nav > li > a").each(function(){
            if ($(this).attr("id") == sessionStorage.getItem("activeMenuItemID")){
                expandMenuItem(this);
            }
        });
    }

    $('#nav > li > a').click(function(elem){
        expandMenuItem(this);
    });

});

function expandMenuItem(elem){
    if ($(elem).attr('class') != 'active'){
        $('#nav li ul').slideUp();
        $('#nav > li > a').removeClass("active");
        $(elem).addClass("active");
        $(elem).next().slideToggle();
        sessionStorage.setItem("activeMenuItemID", $(elem).attr("id"));
    }
}
</script>

the image at the top is not part of the menu at all

Check out this fiddler Here

Ok there are a few things you are missing here that I have fixed in your code just wanted you to know.

Is there a reason expandMenuItem is in the global scope? this can be bad because now no one else can declare an function called expandMenuItem? maybe outside the scope of your project just something to think about.

Try not to use == in js as it has a different meaning than you probably think, use === instead much safer. jquery has a hasClass function that will check to see if an element has a class. the $(elem).attr('class') != 'active' is bad because if it had two classes you'd be SOL.

When asking for the same element in the same function try to save it to a variable. I noticed $(elem) is getting hit a few times. This can cause problems because you keep asking the document for the element, just save it in a variable so you don't have to keep bothering the document. Also your selector #nav > li > a is not correct. You may want to look up what > does for selectors I have switched this as well.

Hope this is helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM