使用jquery将class =“active”添加到html元素

时间:2017-07-01 18:11:50

标签: jquery html

我在php外部文件中有我的标题,链接到网站页面。 当我点击它添加活动类但它不会保持活动...我不知道我做错了什么! 有人可以帮帮我吗? 这是我的代码:

HTML(在php文件中):

<ul class="site-header__list">
    <li class="site-header__item">
      <a class="site-header__link" href="index.php">Home</a>
    </li>
    <li class="site-header__item">
      <a class="site-header__link" href="portfolio.php">Portfólio</a>
    </li>

    <li class="site-header__item">
      <a class="site-header__link" href="empresa.php">Empresa</a>
    </li>

    <li class="site-header__item">
      <a class="site-header__link" href="contactos.php">Contactos</a>
    </li>
  </ul>

JQUERY:

$('.site-header__item a').on('click', function() {
  $(this).addClass('active');
  $(this).sibling().removeClass('active');
});

2 个答案:

答案 0 :(得分:-1)

jQuery(document).on("ready page:change", function() {

  if(window.location.href.indexOf("index.php") > -1 ){ //or You full URL

      jQuery('.site-header__item a').addClass('active'); 
      //or other .site-header__item a 
      //ps. better use id not class or add some one more unique class for every button
      // as this will add class active to all '.site-header__item a'
  }

});

是的,这是因为在开启('点击')事件之后您的页面重新加载。

答案 1 :(得分:-1)

以下代码将根据请求的网址加载页面时适当设置活动类:

<script type="text/javascript">
  $(function() {
    // Set active state on menu element
    var current_url = window.location.href.split('?')[0];
    var full_url = current_url + location.search;
    var $navLinks = $("ul.site-header__list li a");
    // First look for an exact match including the search string
    var $curentPageLink = $navLinks.filter(
      function() {
        return $(this).attr('href') === full_url;
      }
    );
    // If not found, look for the link that starts with the url
    if (!$curentPageLink.length > 0) {
      $curentPageLink = $navLinks.filter(
        function() {
          return $(this).attr('href').startsWith(current_url) || current_url.startsWith($(this).attr('href'));
        }
      );
    }
    // If still not found, look for links that contain the page name only
    if (!$curentPageLink.length > 0) {
      $curentPageLink = $navLinks.filter(
        function() {
          return $(this).attr('href').match(current_url) ||
            current_url.match($(this).attr('href'));
        }
      );
    }
    $curentPageLink.parents('li').addClass('active');
  });
</script>

我们在所有应用程序中都使用它,它运行良好:

enter image description here