如何在Javascript中选择生成的元素

When I click start,some choices will be displayed.

I would like to select each choice by getElementById is it possible?

我该如何改变自己的工作来实现呢?

谢谢

      
    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>
评论
念念不忘
念念不忘

当元素出现在DOM中时,应将事件附加到元素上。此外,属性ID在文档中必须唯一。

您可以尝试以下方式:

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>
点赞
评论