简体   繁体   中英

HTML Anchor tag stops working when className is changed in javascript

I am trying to intercept a click on an tag to change the CSS class when it is selected and then I would like the process to continue to the href specified in the statement. I have created a javascript function which changes the classes for the three links of interest but for some reason, the links do not perform their default action of jumping to the address specified in href. The class values change as expected. Can anyone see what I'm doing wrong?

The HTML (part of a cshtml view):

ul class="nav nav-tabs" id="myTab">
<li class="nav-item">
    <a class="nav-link active nav-data-tab" onclick="setActiveTab(1)" id="NI-ColonyData" data-toggle="tab" href="#ColonyData"><h4>Colony Data</h4></a>
</li>
<li class="nav-item">
        <a class="nav-link" onclick="setActiveTab(2)" id="NI-Weather" data-toggle="tab" href="#Weather"><h4>Weather</h4></a>
</li>
<li class="nav-item">
        <a class="nav-link" onclick="setActiveTab(3)" id="NI-Actions" data-toggle="tab" href="#Actions"><h4>Actions</h4></a>
</li>
<li class="nav-item" hidden>
    <a class="nav-link" data-toggle="tab" href="#Pesticide">Pesticide</a>
</li>

Javascript here:

function setActiveTab(tabNum) {
    var CD = document.getElementById('NI-ColonyData');
    var W = document.getElementById("NI-Weather");
    var A = document.getElementById("NI-Actions");

    if (tabNum == 1) {
        CD.className = "nav-link active nav-data-tab";
        W.className = "nav-link";
        A.className = "nav-link";

    }
    else if (tabNum == 2) {
        CD.className = "nav-link";
        W.className = "nav-link active nav-data-tab";
        A.className = "nav-link";
    }
    else if (tabNum == 3) {
        CD.className = "nav-link";
        W.className = "nav-link";
        A.className = "nav-link active nav-data-tab";
    }
}

Thanks for the responses. Appreciate GrafiCode showing the simple stand-alone code worked. I believe the issue was a conflict with bootstrap so I changed my approach to eliminate the js and just add some local css which is selected using the same selectors as in bootstrap when the tab is pressed.

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