如何在JavaScript中选择生成的元素[重复]

问题描述 投票:0回答:1

当我单击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>
javascript
1个回答
0
投票

您可以尝试以下方式:

    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>
© www.soinside.com 2019 - 2024. All rights reserved.