Create breadcrumbs dynamically on client side using javascript

妖精的绣舞 提交于 2019-12-03 03:55:50

When you are adding the items to the breadcrumb you are not adding them as links, you are just adding text and the click events you had binded to the li elements will not passed along. Finally, you are not giving any sort of href for those breadcrumbs to use.

Try something like this and put it on 4 pages with those links and the script file on each page

<div id="breadcrumb"></div>
<ul id="navigation_links">
    <li><a href="page1.html">Page 1</a></li>
    <li><a href="page2.html">Page 2</a></li>
    <li><a href="page3.html">Page 3</a></li>
    <li><a href="page4.html">Page 4</a></li>
</ul>

JS

$(document).ready(function(){
    bindEventToNavigation();
    showBreadCrumb(); //Show the breadcrumb when you arrive on the new page
});

function bindEventToNavigation(){
    $.each($("#navigation_links > li > a"), function(index, element){
        $(element).click(function(event){
            breadcrumbStateSaver($(this).attr('href'), $(this).text());
            showBreadCrumb();
        });
    });
}

function breadcrumbStateSaver(link, text) {
    if (typeof (Storage) != "undefined") {
        if (sessionStorage.breadcrumb) {
            var breadcrumb = sessionStorage.breadcrumb;
            sessionStorage.breadcrumb = breadcrumb + " >> <a href='" + link + "'>" + text + "</a>";
        } else {
            sessionStorage.breadcrumb = "<a href='" + link + "'>" + text + "</a>";
        }
    }
}

This is only going to put links on pages after the first one. So alternatively you can use

$(document).ready(function () {
    breadcrumbStateSaver(document.title, document.location.href);
    showBreadCrumb();
});

at the top of each page and automatically add it to the breadcrumb instead of doing it on the click. If you need the clicks to run some other function/event you can use span/li/div tags with an id that you can bind an event to instead of just using anchors.

Finally, this will not stop there from being duplicates in the crumb, so you may want to consider storing the links & text in an array and build the crumbs from that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!