简体   繁体   English

使用javascript在客户端动态创建面包屑

[英]Create breadcrumbs dynamically on client side using javascript

I want to create breadcrumbs dynamically on client side using java script .我想使用 java script 在客户端动态创建面包屑 The breadcrumbs will be the path followed by user while navigation as: Home > about us > our history..面包屑将是用户在导航时遵循路径主页>关于我们>我们的历史..

The anchor tags will be generated on each page in the sequence in which the user navigate.锚标记将按照用户导航的顺序在每个页面上生成。

Now I can create these breadcrumbs using server side technology easily but I want to generate it dynamically on each page on client side.现在我可以轻松地使用服务器端技术创建这些面包屑,但我想在客户端的每个页面上动态生成它。 Now I don't know exactly how to implement it.现在我不知道如何实现它。

Some logic in my mind is as:我脑子里的一些逻辑是:

  1. Create an object type variable in java script with a name and value pair where name is the name of current page and value is the url of that page .使用名称值对在 java 脚本中创建一个对象类型变量,其中name当前页面的名称, value是该页面url

  2. Now pass this object variable using query string while navigating from one page to other.现在在从一页导航到另一页时使用查询字符串传递此对象变量。

  3. Then in the second page get that object variable from query string and extract the name and value pair from that object and then using that create the anchor and add it to targeted div (place holder).然后在第二页中从查询字符串中获取该对象变量并从该对象中提取名称和值对,然后使用它创建锚点并将其添加到目标 div(占位符)。

  4. Again when user goes to another page add the name and value pairs for all the previous pages along with the name and value pair for current page at the last in the object variable and pass it to next page using query string .再次,当用户转到另一个页面时,所有先前页面名称和值对以及对象变量中最后一个当前页面的名称和值对添加对象变量中,并使用查询字符串将其传递到下一页。

  5. Now in next page do the same and create anchors.现在在下一页做同样的事情并创建锚点。

Some what similar I got here using html5 client side storage as: html:我在这里使用 html5 客户端存储得到了一些类似的东西: html:

<ul id="navigation_links">
    <li>Page1</li>
    <li>Page2</li>
    <li>Page3</li>
</ul>

js: js:

$(document).ready(function(){
    bindEventToNavigation();
});

function bindEventToNavigation(){
    $.each($("#navigation_links > li"), function(index, element){
        $(element).click(function(event){
            breadcrumbStateSaver($(event.currentTarget).html());
            showBreadCrumb();
        });
    });
}


function breadcrumbStateSaver(text){
    //here we'll check if the browser has storage capabilities
    if(typeof(Storage) != "undefined"){
        if(sessionStorage.breadcrumb){
            //this is how you retrieve the breadcrumb from the storage
            var breadcrumb = sessionStorage.breadcrumb;
           sessionStorage.breadcrumb = breadcrumb + " >> "+text;
        } else {
           sessionStorage.breadcrumb = ""+text; 
        }
    }
    //if not you can build in a failover with cookies
}

function showBreadCrumb(){
     $("#breadcrumb").html(sessionStorage.breadcrumb);   
}
<div id="breadcrumb"></div>

but here instead of creating hyperlinked anchors it is creating simple text, whereas I want the breadcrumbs to be anchors and hyperlinked to their respective pages.但这里不是创建超链接的锚点,而是创建简单的文本,而我希望面包屑成为锚点并超链接到它们各自的页面。

I am new to java script and don't know how to implement this.我是 Java 脚本的新手,不知道如何实现。 If you have any better logic and solution for this please tell me.如果您对此有更好的逻辑和解决方案,请告诉我。

thanks in advance.提前致谢。

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.当您将项目添加到面包屑时,您不会将它们添加为链接,您只是添加文本,并且您绑定到 li 元素的点击事件不会传递。 Finally, you are not giving any sort of href for those breadcrumbs to use.最后,您没有为这些面包屑提供任何类型的 href 以供使用。

Try something like this and put it on 4 pages with those links and the script file on each page试试这样的东西,把它放在 4 页上,每个页面上都有这些链接和脚本文件

<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 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.如果您需要点击来运行其他一些函数/事件,您可以使用带有 id 的 span/li/div 标签,您可以将事件绑定到该标签,而不仅仅是使用锚点。

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.最后,这不会阻止面包屑中的重复,因此您可能需要考虑将链接和文本存储在数组中并从中构建面包屑。

Like @Luke said, you are not adding any links for the breadcrumbs to navigate.就像@Luke所说的那样,您没有为面包屑导航添加任何链接。 You have to store the text and link like so:您必须像这样存储文本和链接:

function breadcrumbStateSaver(link, text) {
if (typeof (Storage) != "undefined") {
    if (sessionStorage.breadcrumb) {
        sessionStorage.breadcrumb = sessionStorage.breadcrumb + ";" + text;
        sessionStorage.locations = sessionStorage.locations + ";" + link; //use any delim you prefer
    }
    else {
        sessionStorage.breadcrumb = text;
        sessionStorage.locations = link;
    }
}

You can just add both the text and link into one storage variable and split it with a delimiter to extract it!您可以将文本和链接都添加到一个存储变量中,然后用分隔符将其拆分以提取它!

Instead of capturing the link on click you can actually get the link when the page loads from document.location.href , and the text can be taken from document.title or some attribute which will be set in server.当页面从document.location.href加载时,您实际上可以获取链接,而不是在点击时捕获链接,文本可以从document.title或将在服务器中设置的某些属性中获取。 So on document.ready所以在 document.ready 上

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

To update the breadcrumbs inside a <ul> :更新<ul>的面包屑:

function showBreadCrumb(){
    let crumbs = sessionStorage.breadcrumb.split(";");
    let links = sessionStorage.locations.split(";");
    for(let index in crumbs)
        $("#navigation_links").append($("<li><a href="+links[index]+">"+ crumbs[index] +"</a></li>"));
}

This way it will it record every time user navigates your website.这样它就会在用户每次浏览您的网站时进行记录。 If you want the user to navigate through the breadcrumbs, by going back to the page they were in by clicking on the breadcrumb, change the above code to the following:如果您希望用户通过面包屑导航,通过单击面包屑返回到他们所在的页面,将上面的代码更改为以下内容:

function showBreadCrumb(){
    let crumbs = sessionStorage.breadcrumb.split(";");
    let links = sessionStorage.locations.split(";");
    let crumbindex = parseInt(sessionStorage.crumbindex);
    for(let index in crumbs){
        $("#navigation_links").append($("<li><a class='crumb"+ (index==crumbindex ? "active" : "") + "' href='"+links[index]+"' data-node='"+index+"'>"+ crumbs[index] +"</a></li>")); //data-node will help in retrieving the index and class will be set to active for selected node
    }
}

also add:还添加:

$(document).ready(function(){
    $('#navigation_links').on('click', 'li a.crumb', function(){
        if (typeof (Storage) != "undefined") {
            sessionStorage.crumbindex = $(this).data('node');
            sessionStorage.navlinkclicked = "true"; //This will prevent from adding breadcrumb again
        }
    });
    breadcrumbStateSaver(document.title, document.location.href);
    showBreadCrumb();
});

Using the node index, you can insert the breadcrumb like so:使用节点索引,您可以像这样插入面包屑:

function breadcrumbStateSaver(link, text) {
if (typeof (Storage) != "undefined") {
    if (sessionStorage.breadcrumb) {
        if (sessionStorage.navlinkclicked && sessionStorage.navlinkclicked=="true") {
            sessionStorage.navlinkclicked = "false"; //prevent changes or you can remove the rest of the crumbs from sessionStorage.breadcrumb and locations using a for loop
        }
        else {
            if(sessionStorage.crumbindex && sessionStorage.crumbindex!=-1) {
                let crumbs = sessionStorage.breadcrumb.split(";");
                let links = sessionStorage.locations.split(";");
                let crumbindex = parseInt(sessionStorage.crumbindex);
                sessionStorage.breadcrumb = crumbs[0];
                sessionStorage.locations= links[0];
                for(let index in crumbs){
                    if(index==0) continue;
                    sessionStorage.breadcrumb = sessionStorage.breadcrumb + ";" + crumbs[index];
                    sessionStorage.locations= sessionStorage.locations + ";" + links[index];
                    if(index==crumbindex) break;
                }
                sessionStorage.breadcrumb = sessionStorage.breadcrumb + ";" + text;
                sessionStorage.locations = sessionStorage.locations + ";" + link; //insert the new link after crumbindex location
                sessionStorage.crumbindex = -1;
            }
            else{
                sessionStorage.breadcrumb = sessionStorage.breadcrumb + ";" + text;
                sessionStorage.locations = sessionStorage.locations + ";" + link; //keep appending
            }
        }
    }
    else {
        sessionStorage.breadcrumb = text;
        sessionStorage.locations = link;
    }
}

If you simply want the breadcrumbs for navigation, rather than recording the users traversal, you can simply split the url path using window.location.pathname .如果你只是想要导航的面包屑,而不是记录用户的遍历,你可以简单地使用window.location.pathname拆分 url 路径。 Given that your pages are stored in proper hierarchy with index pages, all you have to do is to split the url path and update showBreadCrumb() accordingly.鉴于您的页面与索引页面存储在适当的层次结构中,您所要做的就是拆分 url 路径并相应地更新 showBreadCrumb()。 You dont need to use session storage!您不需要使用会话存储!

    function showBreadCrumb(){
        let crumbs = window.location.pathname.split("/");
        for(let index=0; index<crumbs.length-1; index++){
            let text = crumbs[index];
            if(index==0) text = "Home";
            $("#navigation_links").append($("<li><a class='crumb"+ (index==crumbs.length-2? "active" : "") +"' href='"+buildRelativeLink(crumbs.length-index)+"'>"+ text +"</a></li>"));
        }
    }
    function buildRelativeLink(level)
    {
        level = level - 1;
        let link="";
        for (let i=1; i<level; i++)
        {
            link=link+ "../"; //Used to navigate one level up towards parent
        }
        return link;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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