如何使用jQuery向菜单项添加活动类

时间:2019-03-25 07:05:51

标签: jquery

如何使用jQuery向菜单添加活动类?我添加了太多的jQuery代码,但没有任何效果。当我单击菜单时,它会工作一秒钟,然后再次删除活动班级。


<nav id="nav-menu-container">

    <ul class="nav-menu">
        <li class=""><a href="<?= DOMAINURL; ?>">Home</a></li>
        <li><a href="<?= DOMAINURL; ?>#about">About Us</a></li>
        <li class="dropdown">
            <a id="translate01" href="<?= DOMAINURL; ?>business-data.php" class="" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Products</a>
            <ul class="dropdown-menu" role="menu">
                <li><a href="<?= DOMAINURL; ?>business-data.php">Business Data</a></li>
                <li><a href="<?= DOMAINURL; ?>people-data.php">People Data</a></li>
                <li><a href="<?= DOMAINURL; ?>hotels-data.php">Hotels Data</a></li>
                <li><a href="<?= DOMAINURL; ?>restaurants-data.php">Restaurants Data</a></li>
            </ul>    
        </li>
        <li><a href="<?= DOMAINURL; ?>#portfolio">Portfolio</a></li>
        <li><a href="<?= DOMAINURL; ?>#testimonials">Testimonials</a></li>
        <li><a href="<?= DOMAINURL; ?>#contact">Contact Us</a></li>
    </ul>

</nav>

>Here are jquery codes below.

--------------------------------------------------------

$(document).ready(function(){
  $('#nav-menu-container ul li a').click(function(){
    $('.nav-menu .menu-active').removeClass('menu-active');
    $(this).closest('li').addClass('menu-active');
    });

});

>代码2,无效

var link = document.location.href.split('/').slice(-1);   // retrieve page name
$('#nav-menu-container  li a.menu-active').removeClass('menu-active');        // remove class 'active'
$('#nav-menu-container  li a[href$="'+link+'"]').parent().addClass('menu-active');// and add it to a matching

>代码3,不起作用

jQuery(document).ready(function($){

var path = window.location.pathname.split("/").pop();
if (path ==''){
    path = 'index.php';
}
var target = $('#nav-menu-container a[href="'+path+'"]');
target.addClass('menu-active');

});

0 个答案:

没有答案