For example, we have some kind of div , when clicking on a link that changes the class in another diva:

 function active(element) { //ΠžΡ‡ΠΈΡ‰Π°Π΅ΠΌ всС ΡƒΠΆΠ΅ Π½Π°ΠΆΠ°Ρ‚Ρ‹Π΅ элСмСнты for (var i = 1; i < N; i++) { var clear = document.getElementById("tab_" + i); clear.className = "cont" + i; } //ΠŸΡ€ΠΈΡΠ²Π°ΠΈΠ²Π°Π΅ΠΌ Π½ΠΎΠ²Ρ‹ΠΉ класс Π½Π°ΠΆΠ°Ρ‚ΠΎΠΌΡƒ элСмСнту var block = document.getElementById("tab_" + element); if (block.className == "cont" + element) { block.className = "cont" + element + " is_active"; } } 
 <div><a href="#" onclick="active('1');">Π‘ΠΌΠ΅Π½ΠΈ мСня</a></div> <div><a href="#" onclick="active('2');">Π‘ΠΌΠ΅Π½ΠΈ мСня</a></div> <div id="tab_1" class="cont1 is_active"> <p>ΠŸΠ΅Ρ€Π²Ρ‹ΠΉ Π΄ΠΈΠ²</p> </div> <div id="tab_2" class="cont2"> <p>Π’Ρ‚ΠΎΡ€ΠΎΠΉ Π΄ΠΈΠ²</p> </div> 

From the code you can see that the active function is called when you click on a specific link through onclick . But how to make a call to this function so that only id in the attributes? How should JS change, except that it will become some kind of "passive" handler? I can be wrong in the wording.

  • one
    You are mistaken, the essence is completely incomprehensible. - Igor
  • @Igor, in short, I just wanted to remove onclick inside the tags, and so that the processing of the click happens somehow different - Pashok

2 answers 2

Maybe a little crutch, but he wrote on his knee.

 [...document.querySelectorAll("a")].forEach((item, index) => { item.addEventListener("click", (e) => { let foo = document.querySelectorAll("p"); for (var i = 0; i < foo.length; i++) { if (foo[i].classList.contains("active")) { foo[i].classList.remove("active"); } else { foo[index].classList.add("active"); } } }); }); 
 .active { background: pink; } 
 <a href="#">Click me 1</a> <a href="#">Click me 2</a> <p>Some text 1</p> <p>Some text 2</p> 

    So, probably, I tried not to touch your original active(element) function.

     function active(element) { //ΠžΡ‡ΠΈΡ‰Π°Π΅ΠΌ всС ΡƒΠΆΠ΅ Π½Π°ΠΆΠ°Ρ‚Ρ‹Π΅ элСмСнты for (var i = 1; i < 3; i++) { var clear = document.getElementById("tab_" + i); clear.className = "cont" + i; } //ΠŸΡ€ΠΈΡΠ²Π°ΠΈΠ²Π°Π΅ΠΌ Π½ΠΎΠ²Ρ‹ΠΉ класс Π½Π°ΠΆΠ°Ρ‚ΠΎΠΌΡƒ элСмСнту var block = document.getElementById("tab_" + element); if (block.className == "cont" + element) { block.className = "cont" + element + " is_active"; } } [].slice.call(document.querySelectorAll('.clickable')) .forEach((el, i) => el.onclick = active.bind(null, i+1)); 
     .is_active{ background-color: red; } 
     <div><a href="#" class='clickable'>Π‘ΠΌΠ΅Π½ΠΈ мСня</a></div> <div><a href="#" class='clickable'>Π‘ΠΌΠ΅Π½ΠΈ мСня</a></div> <div id="tab_1" class="cont1 is_active"> <p>ΠŸΠ΅Ρ€Π²Ρ‹ΠΉ Π΄ΠΈΠ²</p> </div> <div id="tab_2" class="cont2"> <p>Π’Ρ‚ΠΎΡ€ΠΎΠΉ Π΄ΠΈΠ²</p> </div>