0

First off, I have read similar issues, the most important being this one: JavaScript click event listener on class.

However, my initial code looks more like the solution of that issue, with the difference that my function needs a parameter.

Basically I had a program with buttons that showed content when clicked and could be nested using Javascript, this was done by having several buttons, each with its respective div and an onclick attribute that toggled a class on said div (probably not the best way to do it), this worked just fine until I used addEventlistener instead of the onclick attribute, as shown below:

var buttons = document.getElementsByClassName('nested-button');
var divs = document.getElementsByClassName('nested-div')
function myFunction(id) {
   document.getElementById(id).classList.toggle("show");
}
for (var i = 0;i<buttons.length;i++){
   buttons[i].addEventListener("click", myFunction(divs[i].id),false);
}

First (using the code seen above), the console said it couldn't read the property id of undefined, however, I solved this by making a var with that same value inside the for loop and then use that var as a parameter, the result was, not very surprisingly, that all the buttons toggled show on the last div, so to fix this, I thought inputting just created a function that did myFunction with that var would be enough since the function would always use the id originally used instead of the value of the var, however, that changed nothing:

for (var i = 0;i<buttons.length;i++){
   var currentDiv = divs[i].id
   buttons[i].addEventListener("click", function() 
   {myFunction(currentDiv)},false);
}

Finally since I found a reply that said the result returned by selectByClassName first index had the whole list, so I tried changing the initial value of i in my original code, but the console still told me it couldn't read the id of undefined.

How should I fix this? (please elaborate, also sorry if my grammar is bad)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

0 Answers0