简体   繁体   English

每次单击都会创建新按钮。 我应该如何为新创建的按钮创建相同的功能

[英]On each click new button has been created. How should I create same functionality for new created buttons

 var clicks = 0;
    function clickME() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;


    var btn = document.createElement("BUTTON");
    var t = document.createTextNode(clicks);

    btn.setAttribute("onClick", clicks);

    btn.appendChild(t);
    document.body.appendChild(btn);


 }
<button type="button" onClick="clickME(**strong text**)">Click me</button>
    <p>Clicks: <a id="clicks">0</a></p>

This is the code that created new button with the counter.这是使用计数器创建新按钮的代码。 Now I want to implement same functionality for each of the new buttons.现在我想为每个新按钮实现相同的功能。 Please guide me.请指导我。

The problem is in this line问题出在这一行

btn.setAttribute("onClick", clicks);

clicks is a variable which counts the clicks, not a function. clicks是计算点击次数的变量而不是function。 You want to instead assign the function to the new button, like this:您想将 function 分配给新按钮,如下所示:

btn.onclick = clickME;

Here's the code: https://codesandbox.io/s/still-frog-0qust这是代码: https://codesandbox.io/s/still-frog-0qust

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

相关问题 javascript如何在创建对象后将新对象添加到对象中 - javascript how to add new object into object after it has been created 为该按钮将创建的每个新行添加i ++ - Add i++ for each new row that will created by the button 创建地图后如何设置Google Maps背景。 map.setOptions()不起作用 - How to set google maps background when the map has already been created. map.setOptions() does not work 如何从管理员为新用户创建的Alfresco UI页面获取密码? - How to fetch password from Alfresco UI page which has been created by admin for the new user? 如何管理每行动态创建按钮的功能? - How to manage the functionality of a dynamically created button with each row? 如何在我创建的原始盒子旁边创建一个新盒子? - How to create a new box beside the original one that I had created? 每次单击按钮即可创建新的随机句子 - Create new random sentence with each click of a button 基于类的按钮单击事件不会在动态创建的按钮上触发。 - Button click event based on class isn't being fired on button that is dynamically created. 每次点击创建3个不同的按钮,以显示新图像 - Create 3 different buttons with each click displays new image 如何为使用 Html5 创建的视频创建灯箱效果? - How do I create a lightbox effect for a video that has been created with Html5?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM