Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

html - JavaScript onClick addClass

I am kind of confused why my code doesn't work correctly, I hope You will tell me what I've done wrong. I want to highlight navigation tab while clicked.

HTML:

<header class="mainheader">
  <!-- Obrazek tutaj-->
  <nav>
    <ul>
      <li><a id="a-home" onclick="dodajAktywne(this)" href="index.html">Home</a></li>
      <li><a id="a-omnie" onclick="dodajAktywne(this)" href="omnie.html">O mnie</a></li>
      <li><a id="a-kurs" onclick="dodajAktywne(this)" href="kurs.html">Kurs</a></li>
      <li><a id="a-kontakt" onclick="dodajAktywne(this)" href="kontakt.html">Kontakt</a></li>
    </ul>
  </nav>
</header>

JavaScript:

   function dodajAktywne(elem) {
    var a = document.getElementsByTagName('a')
    for (i = 0; i < a.length; i++) {
        a[i].classList.remove('active');
    }
    elem.classList.add('active');
}

CSS:

.active {
    color: blue;
    background-color: #cf5c3f;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simplify your JavaScript to:

Fiddle

function dodajAktywne(elem) {
    // get all 'a' elements
    var a = document.getElementsByTagName('a');
    // loop through all 'a' elements
    for (i = 0; i < a.length; i++) {
        // Remove the class 'active' if it exists
        a[i].classList.remove('active')
    }
    // add 'active' classs to the element that was clicked
    elem.classList.add('active');
}

If you pass the parameter this in your HTML to:

<header class="mainheader">
    <!-- Obrazek tutaj-->
    <nav>
        <ul>
            <li><a id="a-home" onclick="dodajAktywne(this)" href="#">Home</a>
            </li>
            <li><a id="a-omnie" onclick="dodajAktywne(this)" href="#">O mnie</a>
            </li>
            <li><a id="a-kurs" onclick="dodajAktywne(this)" href="#">Kurs</a>
            </li>
            <li><a id="a-kontakt" onclick="dodajAktywne(this)" href="#">Kontakt</a>
            </li>
        </ul>
    </nav>
</header>

Note: I've changed href attribute to #, you will have to change it back to your .html pages


Alternatively, you can do this without JavaScript, using CSS's :focus:

Fiddle

a:focus {
    color: blue;
    background-color: #cf5c3f;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...