[英]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.