Dynamic breadcrumb based on current page using Javascript/jQuery

牧云@^-^@ 提交于 2019-12-10 11:24:44

问题


I've looked at the question here and the answer looked good enough if one doesn't have to actually navigate too.

I need a Javascript/jQuery script that, based on the URL of the current page, can create breadcrumbs with the parents of that page, IE:

 <nav class="items">
 <ul>
 <li><a href="test.html">Test 1</a></li>
 <li><a href="test2.html">Test 2</a>
    <ul>
        <li><a href="level1.html">Level 1</a></li>
        <li><a href="test/level2.html">Level 2</a>
            <ul>
                <li><a href="test/level2/level3.html">Level 3</a></li>
                <li><a href="test/level2/level32.html">Also at level 3</a></li>
            </ul>
      </li>
    </ul>
 </li>
 <li><a href="test3.html">Test 3</a></li>
</ul>
</nav>

If the user navigates to Level 3, based on current page, show:

Home >> Test 2 >> Level 2 >> Level 3

This script will be included in every page, so it works onload.


回答1:


You can try following code in the document ready event of the page.

var url = "level3.html"; <-- following line shows how to get this from url
//location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
var currentItem = $(".items").find("[href$='" + url + "']");
var path = "home";
$(currentItem.parents("li").get().reverse()).each(function () {
    path += "/" + $(this).children("a").text();
});
$(".bredcrumb").html(path);

Demo

Incase if you want breadcrumb with navigation links try this Demo




回答2:


If you are going to navigate on http request this code may not work well for you.

If you are going to have html pages to navigate via this menu; you may have some code working on load of every html page you have, to build breadcrumb according to that page.

But if you are going to navigate content via ajax you can use this code. And put your content load function inside on click event.



来源:https://stackoverflow.com/questions/25844332/dynamic-breadcrumb-based-on-current-page-using-javascript-jquery

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