如何在使用哈希时为当前页面添加任何特定类

问题描述 投票:0回答:3

我有三个单独的链接用于同一页面。

基于当前页面URL考虑HASH(#),我想使用jQuery代码在LI和Anchor标签中添加类。

在代码下方使用但不起作用。

<ul class="menu">
<li><a href="https://example.com/faq">faqs</a></li>
<li><a href="https://example.com/assistance#pay_navi_method">payment methods</a></li>
<li><a href="https://example.com/assistance#service_center">service centre</a></li>
<li><a href="https://example.com/assistance#cust_delight">hotline</a></li>
<li><a href="https://example.com/assistance">assistance</a></li>
</ul>

试试1:

jQuery(window).on('hashchange', function() {
  var hash = window.location.hash;
  jQuery('a').closest('li').removeClass('called');
  jQuery('a[href="' + hash + '"]').closest('li').addClass('called');
});

试试2:

jQuery(function() {
  jQuery('ul.menu li a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('called');
});
jquery html
3个回答
2
投票

你可以这样做:

<div id="foo">
    <a href="#foo">Foo</a>
</div>

<script>
    jQuery(document).ready(function()
    {
        $(window).on('hashchange', function()
        {
            var hash = window.location.hash.substr(1);
            $('a[href="#'+ hash +'"]').closest('div').css('background', 'red')
        });
    })
</script>

这是功能的一个示例 - 根据您的代码进行调整。

基本上发生的是,在页面加载时 - 您的网址很可能不包含哈希值(除非用户已经在page.php#位置)。

你的第一次尝试非常接近,我只是想你是怎么得到哈希是你的错。


2
投票

您可以使用jQuery执行此操作,只需使用CSS选择器,如下所示:

a[href$="#cust_delight"] { color: red; }

使用a[href$=""]选择器,您可以根据锚点href值的末尾匹配元素。

在你的例子中,你使用^开头,另一个你错过了 - 所以选择器不匹配


1
投票

您可以使用url添加类,如下所示

// Fetch current URL
var current_location = window.location.href;

// iterate each <a> of li to add class 'active' to matched element.
$(".menu li").each(function() {
  if ($(this).children("a").attr("href") == current_location) {
    $(this).addClass("active");
    $(this).children("a").addClass("active");
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.