This is not a duplicate question.
I have a list of buttons that I want to pass a unique value into when it's dynamically generated as shown below.
Expected outcome: I want the alert to show "Hello World" plus Index Of The Button when it was generated.
Current Outcome: alert is constantly showing "Hello World 20". 20 being the last index of the for loop.
<!DOCTYPE html> <html> <body onload="genManyBtns()"> <p>Click the button to show an Alert Corresponding to it's Index</p> <script> function genManyBtns() { for (var i = 0; i < 20; i++) { var btn = document.createElement("BUTTON"); btn.innerHTML = "CLICK ME"; btn.onclick = function() { alert("Hello World " + i) }; document.body.appendChild(btn); } } </script> </body> </html>
You are using vanilla JavaScript. In order to use the index, you can save it in an attribute. I created a data-index-button
attribute in order to get it and use it to show the index of the button when it is clicked.
function genManyBtns() {
for (var i = 0; i < 20; i++) {
var btn = document.createElement("BUTTON");
btn.setAttribute("data-index-button", i);
btn.innerHTML = "CLICK ME";
btn.onclick = function() {
var index_button = this.getAttribute("data-index-button");
alert("Hello World " + index_button);
};
document.body.appendChild(btn);
}
}
You have to write another method for button onclick
. I just update your code with clickMe()
method. Try this I hope it'll help you out. Thanks
<!DOCTYPE html> <html> <body onload="genManyBtns()"> <p>Click the button to show an Alert Corresponding to it's Index</p> <script> function genManyBtns() { for (var i = 0; i < 20; i++) { var btn = document.createElement("BUTTON"); btn.innerHTML = "CLICK ME"; btn.className = "clickMe"; btn.setAttribute('data-index', i); document.body.appendChild(btn); } } document.addEventListener('click', function (e) { if (e.target.matches('.clickMe')) { e.preventDefault(); alert("Hello World " + e.target.dataset.index); } }, false); </script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.