简体   繁体   English

如何为HTML Button动态设置onClick事件并传入唯一值

[英]How to dynamically set onClick event for HTML Button and pass in a Unique Value

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. 预期结果:我希望警报显示“Hello World”以及生成时按钮的索引。

Current Outcome: alert is constantly showing "Hello World 20". 当前结果:警报不断显示“Hello World 20”。 20 being the last index of the for loop. 20是for循环的最后一个索引。

 <!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. 您正在使用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. 我创建了一个data-index-button属性以获取它,并在单击它时使用它来显示按钮的索引。

    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 . 您必须为button onclick编写另一种方法。 I just update your code with clickMe() method. 我只是用clickMe()方法更新你的代码。 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM