如何使用javascript创建面包屑



我是javascript的新手,所以我知道我错过了一些东西,但我就是说不出我错过了什么。

我正在为 Adobe Muse 创建一个小部件,并希望用户能够在小部件中添加或删除痕迹导航。该小部件允许用户设置真值或假值,我正在使用 document.write 函数编写代码。该小部件使用 schema.org 标记,因此itemprop itemscope什么都没有。

下面是脚本的外观

<script type="text/javascript">
    var crumb2 = "true";
    var crumb3 = "true";
        if (crumb2 == "true") {
            document.write("<span>Crumb2</span><span itemscope itemtype='http://data-vocabulary.org/Breadcrumb'><a href='crumb2.html' itemprop='url'><span itemprop='title'>Crumb2 Title</span></a></span>");
        } else if (crumb3 == "true") {
            document.write("<span>Crumb3</span><span itemscope itemtype='http://data-vocabulary.org/Breadcrumb'><a href='crumb3.html' itemprop='url'><span itemprop='title'>Crumb3 Title</span></a></span>");
        }
</script>

据我所知,一旦第一个变量被读为true,它将忽略其余变量(至少当代码以我编写的方式编写时)。假设这是真的,我怎么能让它不这样做(因为缺乏正确的术语)?

为什么document.write?一定有更好的方法。

也就是说,您的问题是,无论前一个条件的结果如何,我如何拥有多个条件过程?答案是不要使用else部分。

if (true) {
  // Will exuecute
} else if (true) {
  // Will never execute
}

if (true) {
  // Will execute
}
if (true) {
  // Will execute
}

为了跟进document.write评论,我不知道Adobe Muse,但如果它在浏览器中,你应该使用DOM API(或jQuery)来管理更改。 document.write是一个非常滑坡和不好的做法。

相反,为什么不像这样的函数:

function makeCrumElement(url, title) {
  var root = document.createElement('span');
  root.setAttribute('itemscope');
  root.setAttribute('itemtype', 'http://data-vocabulary.org/Breadcrumb');
  var aTag = document.createElement('a');
  aTag.setAttribute('itemprop', 'url');
  aTag.setAttribute('href', url);
  var spanTitle = document.createElement('span');
  spanTitle.setAttribute('itemprop', 'title');
  var titleText = document.createTextNode(title);
  spanTitle.appendChild(titleText);
  aTag.appendChild(spanTitle);
  root.appendChild(aTag);
  return root;
}

或使用innerHTML

function makeCrumElement(url, title) {
  var root = document.createElement('span');
  root.setAttribute('itemscope');
  root.setAttribute('itemtype', 'http://data-vocabulary.org/Breadcrumb');
  root.innerHTML = '<a href="' + url + '" itemprop="url"><span itemprop="title">' + title + '</span></a>';
  return root;
}

或者使用 jQuery:

function makeCrumElement(url, title) {
  var root = $('<span><a><span></span></a></span>')
    .attr({
      itemscope: true,
      itemtype: 'http://data-vocabulary.org/Breadcrumb'
    });
  root.find('a')
    .attr({
      itemtype: 'url'
      href: url
    })
    .find('span')
    .attr({
      itemprop: 'title'
    })
    .text(title);
  return root;
}

最新更新