简体   繁体   中英

“next”-link based on hash url. (javascript)

I'm kinda new to javascript and have a list of links as a menu, the last button is meant to be a next button, who will go to the next link in line dependent on which page or #hash you are on currently.

    <li><a class="menu" href="#home"><div>Home</a></li>
    <li><a class="menu" href="#work">Work</a></li>
    <li><a class="menu" href="#about">About</a></li>
    <li><a class="menu" href="#">Next</a></li>

So if forexample you're on the work page, the next button would send you to the about page, and if you're on the about page, it would send you to the home page.

I guess it has something to do with a array, and some javascript, since it has to work live, but no idea how to do it.

Hope someone could explain or give me a hint.

Thanks in advance!

This is quite easy, and doesn't need any additional arrays:

$("#next").on("click", function (e) {
    e.preventDefault();
    var currentLink = location.hash ? $("a.menu[href=" + location.hash + "]") : null,
        next = currentLink ? currentLink.parent().next() : null;
    if (!next || next.children().attr("id") == "next") {
        next = $("a.menu").first().parent();
    }
    if (next) {
        location.hash = next.children().attr("href");
    }
});

(I've given the “next”-link the id next to make it easily target-able.)

What it does:

If location.hash contains a value, it tries to find the a.menu element with the according href .
If it's found that, it gets the the next LI . If it has found nothing, or the LI found contains the a:next link, then it gets the first LI .

And finally, it assigns the href value of the found LI 's (if any) first child to location.hash .

See fullscreen version here to actually see the hash change: http://jsfiddle.net/ve9qt/3/show/ , and http://jsfiddle.net/ve9qt/3/ for the full code.

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