+ 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.
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
+ 6
Josh Bremer Stop being stupid or Mods will use you as a volunteer of their invisibility magic.
+ 1
solo se el Español de España ok ?.
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
0
vnbmhl
- 1
Яв0хх txip
- 2
using magic