【问题标题】:how can I get ID of element which I created by js [duplicate]如何获取由 js 创建的元素的 ID [重复]
【发布时间】:2021-08-17 23:59:13
【问题描述】:

希望你们都没事,在我下面的代码中: 用户每次点击元素 --> #crBtn,应该创建一个具有不同 id 的新按钮(但都具有相同的 className),例如,如果用户点击 #crBtn 三次,则意味着将出现 3 个按钮,现在,如果我点击这些按钮中的任何一个,我希望它改变它的背景颜色,同时我需要它的 id,我该如何在 js 中做到这一点?

var idNum = 0;
  
    
  function crBtn()
  {
  idNum++;
  var button = document.createElement("button");
  button.innerHTML="HERE";
  button.setAttribute("class","name");
  button.setAttribute("id","na"+idNum);
  document.body.appendChild(button); 
  }
 .name
{
 background-color: aquamarine;
border: none;
width:300px;
height: 50px;
cursor: pointer;
margin-right: 10px;
margin-bottom:10px;
}
#crBtn
{
width:500px ;
height:60px;
background-color: blue;
border: none;
margin:30px;
color:white;
font-size: 30px;
}
.name:hover
{
background-color: skyblue;
color:aliceblue;
}
 <body>
 <button id = "crBtn" onclick="crBtn()">CLICK TO CREATE BUTTONS</button><br>
 </body>

【问题讨论】:

    标签: javascript html css createelement


    【解决方案1】:

    以下脚本定义了一个委托点击处理程序,绑定到文档的正文元素。根据单击的按钮采取不同的操作。

    var idNum = 0;
    document.body.onclick=ev=>{
      if (ev.target.id==="crBtn") crBtn()
      else if (ev.target.className==="name") {
        console.log("click on button with ID "+ev.target.id)
        ev.target.style.backgroundColor="red";
      }
    }
    
    function crBtn(){
      idNum++;
      var button = document.createElement("button");
      button.innerHTML="HERE";
      button.setAttribute("class","name");
      button.setAttribute("id","na"+idNum);
      document.body.appendChild(button); 
    }
    .name
    {
     background-color: aquamarine;
    border: none;
    width:300px;
    height: 50px;
    cursor: pointer;
    margin-right: 10px;
    margin-bottom:10px;
    }
    #crBtn
    {
    width:500px ;
    height:60px;
    background-color: blue;
    border: none;
    margin:30px;
    color:white;
    font-size: 30px;
    }
    .name:hover
    {
    background-color: skyblue;
    color:aliceblue;
    }
    <body>
     <button id="crBtn">CLICK TO CREATE BUTTONS</button><br>
     </body>

    【讨论】:

      【解决方案2】:

      event 传递给函数。 event 对象的target 属性是您单击的元素。

      <button id = "crBtn" onclick="crBtn(event)">CLICK TO CREATE BUTTONS</button><br>
      
      function crBtn(e){
        console.log(e.target); //e.target is the button element
      }
      

      【讨论】:

      • 你好,谢谢你的回答,我不想要#crBtn的id,我想得到函数crBtn()创建的按钮的id{}
      猜你喜欢
      • 2015-11-12
      • 1970-01-01
      • 2017-08-24
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      相关资源
      最近更新 更多