将搜索结果URL显示为面包屑



我需要在搜索列表中以面包屑样式显示URL(例如,Google do -die -google backcrumbs),并且对JavaScript的了解有限(并且尚未触摸它在近两年内)。你能帮我吗?如果代码提供了明确的指示,我可以应用该代码,并且对HTML和CSS非常舒适,但没有尝试过没有列表的面包屑。

我从哪里开始?

输入将是页面的URL(类是.slimbreadcrumblink) - 例如。https://www.example.com/level1/level2/level2/level3/level4-且输出如下:

级别2>级别3>级别4

我还没有尝试过任何意义,我从这里开始。我已经阅读了其他提出的面包屑问题,但到目前为止没有帮助。我找到了以下内容,但不知道该如何实施。

var path = location.pathname;
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
  });
}

谢谢。

我滚动了自己的演示片段。该代码可以解释很多,但是如果没有任何东西看起来不言自明,请随时让我知道,我将在这里详细说明。

// Utility functions
function createBreadcrumbs (origin, path) {
    var levels = path.slice(1).split('/')
    
    return levels.map(function (e, i, levels) {
      var text = e.replace(/-+/g, ' ').replace(/s*bS/g, function (e) {
          return e.toUpperCase()
      })
      return anchor(origin + '/' + levels.slice(0, i+1).join('/'), text)
    })
}
function anchor (href, text) {
    var a = document.createElement('a')
    a.href = href
    a.textContent = text
    return a
}
function render (breadcrumbs) {
  var ol = document.createElement('ol')
  ol.className = 'breadcrumbs'
  breadcrumbs.forEach(function (anchor) {
      var li = document.createElement('li')
      anchor.className = 'breadcrumbs__link'
      li.className = 'breadcrumbs__crumb'
      li.appendChild(anchor)
      ol.appendChild(li)
  })
  return ol
}
// How to use
var breadcrumbs = createBreadcrumbs('//example.com', '/example-thing/location-stuff/level-2'),
    list = render(breadcrumbs)
console.log(breadcrumbs)
document.body.appendChild(list)
<p>Breadcrumbs for <a href="//example.com/example-thing/location-stuff/level-2">//example.com/example-thing/location-stuff/level-2</a></p>

这是一个功能,它将为面包屑创建HTML结构:

const getLevels = url => url.replace(/http(s.):///, "").split("/");
const createBreadcrumb = function(url, elem) {
    const ol = document.createElement("ol");
        getLevels(url).forEach((e, i) => {
            if(i > 2) {
                const li = document.createElement("li");
                const a  = document.createElement("a");
                a.href = url.substring(0, url.indexOf(e) + e.length);
                a.innerText = e;
                li.appendChild(a)        
                ol.appendChild(li);
            }   
        }
    });
    elem.appendChild(ol);
};

因为它是ES6,因此您必须使用像Babel这样的转板器使其与较旧的浏览器兼容。另外,由于您正在解析URL,因此无法自定义链接标题。

您可以使用这样的函数来解析url并使用id中的元素中创建ol列表。

createBreadcrumb(url, document.getElementById("id"));

最新更新