How could I pass a JavaScript function without directly saying its name?

Say I have a hundred functions and a hundred HTML buttons and I want to assign them all to their click events.

I could name them like button1, button2, button3, ... and function1, function2, function3 ...

Then say:

let btsn = document.getElementsByClassName("mybuttons");
for (int i = 0; i < 100; i++) {
    btns[i].addEventListener("click", "function" + i);
}

Of course this doesn't work because a string literal doesn't get translated into an actual reference to the function, it's just me stating its name randomly and gets forgotten.

But is there some way I could achieve this as though that were possible?


edit:

The exact functionality I was looking for can be done by putting the functions in an array.

let funcs = [
    function a() { ; }
    function b() { ; }
    function c() { ; }
    function d() { ; }
    function e() { ; }
]
let btsn = document.getElementsByClassName("mybuttons");
for (int i = 0; i < 100; i++) {
    btns[i].addEventListener("click", funcs[i]);
}


Read more here: https://stackoverflow.com/questions/63381266/how-could-i-pass-a-javascript-function-without-directly-saying-its-name

Content Attribution

This content was originally published by zachary at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: