问题
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