+ 16

JAVASCRIPT - How could I call a specific class between links?

Sample code: HTML <a href='#' class='link'>Link1</a> <a href='#' class='link'>Link2</a> <a href='#' class='link'>Link3</a> JS const link = document.getElementsByClassName('link'); link[?].onclick = function(){ // if statements } How would I specify a class when it's clicked? See the '?' on the onclick code.

21st Sep 2018, 11:45 PM
Email Not Activated
7 ответов
+ 19
Iterate each of the class elements and use bind to add each class parameters into the respective callback functions. <a href='#' class='link'>Link1</a> <a href='#' class='link'>Link2</a> <a href='#' class='link'>Link3</a> <script> const link = document.getElementsByClassName('link'); for(var i=0;i<link.length;i++) { link[i].onclick = function(num){ // if statements alert("Link " + (num+1) + " is clicked."); this.style.color = "red"; }.bind(link[i],i); } </script> https://code.sololearn.com/Wpfro76FJD80/?ref=app
22nd Sep 2018, 12:27 AM
Calviղ
Calviղ - avatar
+ 6
Josh Bremer Stop being stupid or Mods will use you as a volunteer of their invisibility magic.
23rd Sep 2018, 11:47 PM
Email Not Activated
+ 1
solo se el Español de España ok ?.
23rd Sep 2018, 3:21 PM
jose reguera infante
jose reguera infante - avatar
0
Hello, I just face the same problem today and here is how I resolve it. <a href='#' class='link'>Link1</a> <a href='#' class='link'>Link2</a> <a href='#' class='link'>Link3</a> <script> const link = document.getElementsByClassName('link'); for(var i=0;i<link.length;i++) { link[i].addEventListener("click", somefuction.bind(null, i+1)); } function somefuction(num) { alert("This is link " + num +".") } </script> https://code.sololearn.com/Wpfro76FJD80
23rd Sep 2018, 10:23 AM
Samuel Hui
Samuel Hui - avatar
0
vnbmhl
1st Oct 2018, 7:11 PM
elham
- 1
Яв0хх txip
23rd Sep 2018, 10:25 AM
Andrii
- 2
using magic
23rd Sep 2018, 9:13 PM
Junky JarJar
Junky JarJar - avatar