I'm quite new in web development, I'm trying to create multiple buttons in a javascript function and define their onclick function in a for loop.
What I want : When I click on the button, I want to recover the value associated with this button.
What I have : When I click on any button, I am recovering the value associated with the last button.
I have made a simple example of what I'm trying to do :
HTML :
<html>
<body>
<div id="container">
</div>
<script src="script.js" charset="utf-8"></script>
</body>
</html>
JS :
const data = [1, 2, 3, 4, 5];
var i;
for (i = 0;i < data.length;i++) {
const root = document.createElement('button');
root.setAttribute("class", "exerciceBox");
root.textContent = i;
root.onclick = function() {
console.log(i);
}
document.getElementById("container").append(root);
}
I don't know if there is a best way to declare .onclick function for button created in JS files or maybe another way to do this.
I hope you could help me ! Thank you in advance, Sincerely, Valentin