简体   繁体   中英

Using jQuery to set active class in PHP

First, why do I always get downvoted when I ask about this question? Here's the question.

I got tag PHP in a href .

Here's my code:

<nav class="main-navi">
<ul>
    <li>
        <a href="?r=site/index" >
            Home
            <span class="dot"></span>
            <span class="corner"></span>
        </a>
    </li>
    <li>
        <a href="?r=site/fotoportfolio">
            Portfolio
            <span class="dot"></span>
            <span class="corner"></span>
        </a>
    </li>
    <li>
        <a href="?r=site/fotoabout">
            About
            <span class="dot"></span>
            <span class="corner"></span>
        </a>
    </li>

    <li>
        <a href="?r=site/fotoservice">
            services
            <span class="dot"></span>
            <span class="corner"></span>
        </a>
    </li>
    <li>
        <a href="?r=site/fotoblog">
            Blog
            <span class="dot"></span>
            <span class="corner"></span>
        </a>
    </li>
    <li>
        <a href="?r=site/fotocontact">
            contacts
            <span class="dot"></span>
            <span class="corner"></span>
        </a>
    </li>
</ul>
<em id="showHideMenu" class="show-hide-menu fa fa-bars" href="#"></em></nav> 

And I include 2 scripts:

<script>
    var loc = window.location.href;
    $('.main-navi ul li a').each(function () {
        var status = loc.indexOf($(this).attr('href')) > -1;
        $(this).toggleClass('active', status);
    });
</script>
<script>
    console.log(location.href);
</script>

The first script function is to give an active class when I load the page, and the second script just to know the link location.

In second script, I have output in console like this:

?r=site/index

And the url is:

localhost/blablabla/frontend/web/?r=site/index

The problem is: I don't have the class active in the navbar whenever I load the page.

Example: If I load index, 'home' doesn't get class active . What am I doing wrong? Thanks.

The toogleClass() is not working as expected for you. Change it to:

if (status) {
    $(this).addClass('active');
}

https://jsbin.com/beyinaxoka/edit?html,js,console,output

I fixed the bug. I only needed to add $(document).ready(function () { }); and it worked like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM