当我单击start
时,将显示一些选择。
我想通过getElementById
选择每个选项吗?
如何更改工作以实现目标?
谢谢
document.getElementById("start").addEventListener('click',function(){
html=" ";
for (let i=1;i<=4; i++){
html+= "<button id='choice'>"+"choice"+i+"</button><br>";
}
document.querySelector('.btn').innerHTML = html;
});
document.getElementById("choice").addEventListener('click',function(){
console.log(this);
});
<div class ="btn"><button id="start">start</button></div>
您可以尝试以下方式:
document.getElementById("start").addEventListener('click',function(){
html=" ";
for (let i=1;i<=4; i++){
html+= `<button id=choice${i}>choice${i}</button><br>`;
}
document.querySelector('.btn').innerHTML = html;
document.querySelectorAll("[id*=choice]").forEach(function(el){
el.addEventListener('click',function(){
console.log(this);
});
});
});
<div class ="btn"><button id="start">start</button></div>