显示带有li下拉列表的所选类别的名称

问题描述 投票:1回答:1

我有一个<li>的下拉列表。我想在类别页面上单击,以查看类别名称,而不是“所有类别”。

目前,我确实有一个选定的类别,但是在浏览器打开选定类别页面时,我不知道如何将“所有类别”更改为选定类别本身。

function dropdownBlogTablet() {
  document.getElementById("myDropdownTablet").classList.toggle("show");
  window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
      var dropdowns = document.getElementsByClassName("dropdown-content-tablet");
      var i;
      for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains('show')) {
          openDropdown.classList.remove('show');
        }
      }
    }
  }
}

jQuery(function() {
  jQuery("#menu-blog-menu li a").click(function() {
    jQuery(this).parent().addClass('selected').siblings().removeClass('selected');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown tablet blog">
  <button onclick="dropdownBlogTablet()" class="dropbtn">All Categories<i id="chevron_down_blog" class="icon"></i></button>
  <div id="myDropdownTablet" class="dropdown-content-tablet">
    <ul id="menu-blog-menu" class="categorie_menu">
      <li><a href="/blog/">All Articles</a></li>
      <li><a href="/blog/category/msp-tips/">MSP Tips</a></li>
      <li><a href="/blog/category/product/">Product</a></li>
      <li><a href="/blog/category/technology/">Technology</a></li>
      <li><a href="/blog/category/cybersecurity/">CyberSecurity</a></li>
      <li><a href="/blog/category/webinars/">Webinars</a></li>
    </ul>
  </div>
</div>

提前感谢!

javascript jquery drop-down-menu dropdown
1个回答
0
投票
All Categories包裹在HTML标记中,以便使用JavaScript轻松定位和更改它(否则很难将其与<i>标记分开):

<button onclick="dropdownBlogTablet()" class="dropbtn"> <span class="dropbtn-title">All Categories</span> <i id="chevron_down_blog" class="icon"></i> </button> 我假设您将代码包含在网站的多个页面上,这就是为什么您希望标题反映当前页面的原因。为此,您需要以下代码:

页面加载时运行

    查看页面的当前路径是否匹配列表中的任何链接
  1. 如果匹配,将
  2. 所有类别更改为指定的标题
  • 下面的其他Javascript代码实现了这一目标(将其添加到现有代码的下面):// 1. Run when the page loads jQuery(function() { // 2. See if the page's current path matches any of the links in the list. var link = document.querySelector('#myDropdownTablet a[href="' + window.location.pathname + '"]'); // 3. If it does match, change All Categories to the specified title. if (link) document.querySelector('.dropbtn-title').textContent = link.textContent; });

    最后,您可能还需要单击链接时立即更改文本的代码(即使在链接加载和页面位置更改之前,该文本仅会显示一秒钟。)>

    为此,将以下行添加到现有的click处理程序中:

    document.querySelector('.dropbtn-title').textContent = this.textContent;

    如果您有任何澄清的问题,请随时提问!

  • © www.soinside.com 2019 - 2024. All rights reserved.