【问题标题】:How to truncate the anchor tag if tags are more than two如果标签超过两个,如何截断锚标签
【发布时间】:2022-01-11 09:23:38
【问题描述】:

我的页面上有以下代码

var menuBreadcrumb = document.getElementById('menu-breadcrumb');

var counta = $("#menu-breadcrumb a").length;
//alert(counta);

if (counta >= 2) {
  let mbcElement = '<a class="mbc-link-back" href="#" data-menu-item-id="">...</a>';
  menuBreadcrumb.insertAdjacentHTML('beforeend', mbcElement);


}
.mbc-link-back {
  color: #0066cc;
  text-decoration: none;
}

#menu-breadcrumb a+a::before {
  color: #222;
  content: '>';
  cursor: default;
  padding: 0 3px;
}
<div id="menu-breadcrumb">
  <a href="">Demo 1</a>
  <a href="">Demo 2</a>
  <a href="">Demo 3</a>
  <a href="">Demo 4</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

我正在做的是,如果anchor 标签大于 2,那么我必须显示 firstlast 锚标签,在中间,我必须显示 ... 并带有可点击。

到目前为止,我有超过 2 个锚标签,所以我的预期输出是

Demo1 > ... > Demo4

如果我有 2 个锚标记,那么我必须显示

Demo1 > Demo2

【问题讨论】:

    标签: javascript html jquery css


    【解决方案1】:

    您可以使用此脚本来实现您的目标:

    let anchors = $("#menu-breadcrumb a");
      if (anchors.length > 2) {
        let mbcElement = $('<a class="mbc-link-back" href="#" data-menu-item-id="">...</a>');
        anchors.not(':first, :last').addClass('inactive');
        anchors.first().after(mbcElement)
      }
    .mbc-link-back {
      color: #0066cc;
      text-decoration: none;
    }
    
    .mbc-link-back {
      color: #0066cc;
      text-decoration: none;
    }
    
    #menu-breadcrumb a+a::before {
      color: #222;
      content: '>';
      cursor: default;
      padding: 0 3px;
    }
    
    #menu-breadcrumb .inactive {
        display: none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="menu-breadcrumb">
      <a href="">Demo 1</a>
      <a href="">Demo 2</a>
      <a href="">Demo 3</a>
      <a href="">Demo 4</a>
    </div>

    如果你想通过点击 ... 来显示隐藏的链接,你可以像这样在 mbcElement 上添加事件监听器:

    mbcElement.on('click', function(){
      $(this).hide()
      $("#menu-breadcrumb a.inactive").removeClass('inactive')
    })
    

    【讨论】:

      猜你喜欢
      • 2018-12-23
      • 2012-03-12
      • 2019-09-24
      • 1970-01-01
      • 2021-12-05
      • 2018-04-20
      • 2021-11-18
      • 1970-01-01
      • 2015-05-14
      相关资源
      最近更新 更多