简体   繁体   中英

Can't set class to active in my navbar using Javascript

I am having trouble with my javascript can anyone help me figure out what I am doing wrong? I am trying to add an active class to my navbar tabs, I just started using php and I have had a lot of trouble with this.

<script>
function activePage(evt) {

    var url = window.location.href;     
    var splitUrl = url.split('/');
    var output = splitUrl[splitUrl.length - 1];
    console.log(output);
    console.log(splitUrl);
    console.log(url);

    if (output === 'index.html') {
        evt.currentTarget.className += " active";
    }

    if (output === 'page1.html') {
        evt.currentTarget.className += " active";
    }

    if (output === 'page2.html') {
        evt.currentTarget.className += " active";
    }

    if (output === 'page3.html') {
        evt.currentTarget.className += " active";
    }
}

window.onload = function () {
    activePage(null, null);
};

<div class="navbar">
  <div class="nav-tab"><a href="#" class="logo">logo</a></div>
  <div class="filler"></div>
  <div class="nav-tab"><a href="index.php" onclick="activePage(event)" class="page">Home</a></div>
  <div class="nav-tab"><a href="page1.php" onclick="activePage(event)" class="page">page1</a></div>
  <div class="nav-tab"><a href="page2.php" onclick="activePage(event)" class="page">page2</a></div>
<div class="nav-tab"><a href="page3.php" onclick="activePage(event)" class="page">page3</a></div>

From this answer , and as the comments said, use classList methods.

if (output === 'index.html') {
    evt.currentTarget.classList.add(" active");
}

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