jQuery generate breadcrumbs from url?

2020-06-23 06:21发布

问题:

Is there a way of getting jQuery to generate breadcrumbs on a page from the url?

So if the site url was: mysite.com/sec1/sec2/page

The breadcrumbs would be something like: Home > Sec1 > Sec2 > Page

Thanks

回答1:

This will create an array you can use to generate breadcrumbs.

var here = location.href.split('/').slice(3);

var parts = [{ "text": 'Home', "link": '/' }];

for( var i = 0; i < here.length; i++ ) {
    var part = here[i];
    var text = part.toUpperCase();
    var link = '/' + here.slice( 0, i + 1 ).join('/');
    parts.push({ "text": text, "link": link });
}

Though, I really think you should be handling this at the server side!



回答2:

var url = 'mysite.com/sec1/sec2/page'; // = location.href
var parts = url.split('/');
parts[0] = 'Home';
var breadcrumb = parts.join(' &gt; ');
$('#breadcrumb').html(breadcrumb);


回答3:

splitted_url = document.url.split('/');

Will give you an array containing each directory, then you can access them like splitted_url[0]



回答4:

jQuery doesn't have any unique URL parsing abilities aside from what JavaScript itself provides. You can get the URL path with:

var path = location.pathname;

Then, you can get the parts of the path with:

var parts = path.split('/');

Then, just loop through the parts and generate your breadcrumb HTML as you see fit.