Hi student,
Sure! This is actually a pretty common problem that everyone encounters at some point in web development. This is what is known as a "scope" issue. Scope is essentially the environment that is known to the software at a given time of execution. What is happening in your example, is that when your onclick
function is executed, it's a different scope than the prizes
and btnNum
variables. By the time the onclick
executes, prizes
and btnNum
are long gone. The onclick
function doesn't "know" about these variables. These variables are out of the scope of the onclick
function.
So to fix this, there are a few things you can do. I've written about a few of the other methods that could be used in some further reading, but for simplicity I only included the solution I would recommend here.
This is what I would consider the cleanest solution. You won't need to loop through your HTML elements in javascript to apply the onclick
function. Instead, you define a function in javascript, and just assign it on the HTML element.
<button id="btn-0" onclick="getPrize(0)">Button 1!</button>
Then you can define the getPrize
function in your javascript and use the provided index to get the prize text.
Again, the main thing to keep in mind is ensuring all the variables you're trying to access at the time a line of code executes are still in scope.
I'm glad to clarify further. If you still wind up stuck, just let me know. Good luck!