我有一个<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>
提前感谢!
<i>
标记分开):<button onclick="dropdownBlogTablet()" class="dropbtn">
<span class="dropbtn-title">All Categories</span>
<i id="chevron_down_blog" class="icon"></i>
</button>
我假设您将代码包含在网站的多个页面上,这就是为什么您希望标题反映当前页面的原因。为此,您需要以下代码:
页面加载时运行
查看页面的当前路径是否匹配列表中的任何链接
- 如果匹配,将
- 所有类别更改为指定的标题
// 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;
如果您有任何澄清的问题,请随时提问!