How to assign a class “active” to the li element based on current URL and click event using jQuery or JavaScript

一世执手 提交于 2019-12-11 19:05:01

问题


I am trying to create a menu where a class "active" is assigned to the page whenever it's selected and loaded. Right now it is applied only to the index page by default.

My menu snippet:

<ul class="nav navbar-nav">
     <li class="active"><a href="http://localhost/wp/index.php">Main</a></li>
     <li><a href="http://localhost/wp/news">News</a></li>
     <li><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>

回答1:


Try this code. Its working at my end.

<script>
jQuery(document).ready(function() {
    jQuery(".nav.navbar-nav li").click(function(){
        jQuery(".nav.navbar-nav li").removeClass('active');
        jQuery(this).addClass('active');
        })
var loc = window.location.href;
 jQuery(".nav.navbar-nav li").removeClass('active');
    jQuery(".nav.navbar-nav li a").each(function() {
        if (loc.indexOf(jQuery(this).attr("href")) != -1) {

            jQuery(this).closest('li').addClass("active");
        }
    });
});     
</script>

<ul class="nav navbar-nav">
     <li class="active"><a href="http://localhost/wp/index.php">Main</a></li>
     <li><a href="http://localhost/wp/news">News</a></li>
     <li><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>



回答2:


i assume if you are using php ur page would be like this. just define a $active variable in each page.

<?php 
//Main.php
 $active = "Main";
?>

<?php 
//news.php
 $active = "News";
?>

<?php 
//Contacts.php
 $active = "Contacts";
?>

Then your html would be like this.

<ul class="nav navbar-nav">
     <li class="<?php echo $active=='Main'? 'active' : ''; ?>"><a href="http://localhost/wp/index.php">Main</a></li>
     <li class="<?php echo $active=='News'? 'active' : ''; ?>"><a href="http://localhost/wp/news">News</a></li>
     <li class="<?php echo $active=='Contacts'? 'active' : ''; ?>"><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>



回答3:


I think this will be better:-

$(".navbar-nav").children("a").click(function(){
    $(".navbar-nav").children("li").removeClass("active");
    $(this).parent("li").addClass("active");
 })



回答4:


i hope this would help you if you can edit your theme.

$slug = basename(get_permalink());

<ul class="nav navbar-nav">
         <li class="<?php echo $slug =='Main_page_slug'? 'active' : ''; ?>"><a href="http://localhost/wp/index.php">Main</a></li>
         <li class="<?php echo $slug =='newpageslug'? 'active' : ''; ?>"><a href="http://localhost/wp/news">News</a></li>
         <li class="<?php echo $slug =='congtactPageslug'? 'active' : ''; ?>"><a href="http://localhost/wp/contacts">Contacts</a></li>
    </ul>

there might be some other way to get current page url or title or id, please check here Link




回答5:


You can do it in PHP.

Steps:

1) Create a multi-dimensional array of menus.

2) Key is the link and value is the text.

3) Get the current page URL.

4) Get the last segment of the url using basename().

5) That will be your current page variable. If its blank, assign it to home page.

6) Loop over menus array.

7) Display menu lis in loop.

8) If current loop items is equal to current page, add class active else, add no class.

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
$menus = array();
$menus['main'] = 'index.php';
$menus['news'] = 'News';
$menus['contacts'] = 'Contacts';
$currentURL = curPageURL();// Get Current url here.
$currentPage = basename($currentURL);
$currentPage = empty($currentPage) ? 'main' : $currentPage;
if (! empty($menus)) {
?>
<ul class="nav navbar-nav">
<?php
    foreach ($menus as $lnk => $txt) {
        $activeCls = ($lnk == $currentPage) ? 'active' : '';
?>
     <li class="<?php echo $activeCls;?>"><a href="http://localhost/wp/<?php echo $lnk;?>"><?php echo $txt;?></a></li>
    <?php
    }
?>
</ul>
<?php
}
?>



回答6:


I think you are looking for this. Tried and tested ,, See the Demo and UPDATED DEMO

    $(".navbar-nav").find("a").click(function(){

               $(".navbar-nav").find("li").removeClass("active");
                $(this).parent("li").addClass("active");




        })

        $( window ).load(function() {


         var which_page=window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
                    $(".navbar-nav").find("a").each(function(){
                    if($(this).attr("href") == which_page)
                    {
                     $(this).addClass("active");

                    }

                   })



        });

UPDATED DEMO




回答7:


Try this jQuery:-

$("div.navbar-nav").on('click', 'li', function() {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
});

If you want to keep last selected value after page load based on anchor tag url then add this lines also.

// get the actual pathname:
var path = location.pathname;
// filter menu items to find one that has anchor tag with matching href:
$('.navbar-nav li').filter(function(){
    return '/' + $('a', this).attr('href') === path;
// add class active to the item:
}).addClass('active');

OR

$(document).ready(function () {
        var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");

        $('.navbar-nav a').each(function () {
            if ($(this).attr('href').toLowerCase() == pageTitle.toLocaleLowerCase())
                $(this).parent().addClass('active');
        });
  });

Hope it will help you :)



来源:https://stackoverflow.com/questions/35077996/how-to-assign-a-class-active-to-the-li-element-based-on-current-url-and-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!