我有以下菜单,并且我尝试根据url设置当前类,但是它无法正常工作,有人知道为什么或者甚至更好的方法来实现这一点,谢谢:
HTML-

 <ul class="dropdown">
                        <li><a id="home" href="/">Home</a></li>
                        <li>
                            <a id="hospitals" href="/hca-hospitals">HCA Hospitals</a>
                            <ul class="sub_menu">
                                <li id="one"><a  href="/hca-hospitals/hospitals-and-outpatients">Hospitals and Outpatients</a></li>
                                <li id="two"><a  href="/hca-hospitals/treatments">Treatments</a></li>
                            </ul>
                        </li>
                        <li>
                            <a id="benefits" href="/platinum-choice-benefits">Platinum Choice Benefits</a>
                            <ul class="sub_menu">
                                <li id="one"><a href="/platinum-choice-benefits/download-voucher">Download Voucher</a></li>
                                <li id="two"><a href="/platinum-choice-benefits/where-you-can-go">Where you can go</a></li>
                            </ul>
                        </li>
                        <li>
                            <a id="find" href="/find-a-hca-consultant">Find a Consultant</a>
                        </li>
                        <li>
                            <a id="contact" href="/contact-hca">Contact</a>
                        </li>
  </ul>


CSS-

ul.dropdown li a.current  { color: #66c2c0;}


jQuery-

  var pathname = $(location).attr('href');

       if (pathname = "/contact-hca") {
            $("ul.dropdown li a#contact").addClass("current");
           $("ul.dropdown li a#find").removeClass("current");
        }
       if (pathname = "/find-a-hca-consultant") {
           $("ul.dropdown li a#find").addClass("current");
           $("ul.dropdown li a#contact").removeClass("current");
       }

最佳答案

您使用的是=而不是===,它实际上是在分配pathname,而不是对其进行比较。解决这个问题。

if (pathname === "/contact-hca") {
  $("ul.dropdown li a#contact").addClass("current");
  $("ul.dropdown li a#find").removeClass("current");
} else if (pathname === "/find-a-hca-consultant") {
  $("ul.dropdown li a#find").addClass("current");
  $("ul.dropdown li a#contact").removeClass("current");
}

09-26 22:36