Javascript事件:getElementByID找不到插入的元素。

时间:2018-02-23 03:56:46

标签: javascript-events javascript-objects

神秘:我似乎无法将id传递给插入的元素,然后使用id删除该元素。我收到错误" Uncaught TypeError:无法读取属性'删除' of null"。所以getElementById(thisCorrection)没有找到addButton.id = thisCorrection定义的元素。怪异!

我要做的是:单击一个按钮,它将插入第二个按钮(b2),通过递增计数器为b2创建一个id,mouseover b2按钮将删除该按钮。在javascript中完成所有操作,而不是jquery。

(我觉得这很简单!)



  
   correctionID=0

   function removeButton(thisCorrection){
           document.getElementById(thisCorrection).remove()
   }

   function checkInput() {
      correctionID += 1;
      thisCorrection="correction" + correctionID.toString();
      var addButton=document.createElement("button");
      addButton.id=thisCorrection;
      addButton.innerHTML="here is the new button";
      addButton.addEventListener ("mouseenter", 
                      removeButton(thisCorrection), false);
      this.parentElement.appendChild(addButton) ;}
   

<div> <button onclick="checkInput()"><span style='background:yellow'>click to add button </span></button> </div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

这是一个更简单的表单,显示令人难以置信的javascript / dom古怪(对于新手)。看起来我将不得不使用Jquery ......

&#13;
&#13;
  
   correctionID=0

   function removeButton(addButton){
         //addButton.remove();  
         // Wow! Uncomment the line above and no new button appears.
         // that's because clicking on button 1 runs 
         // removeButton even though the event is 
         // attached to the new button not to button 1!
         console.log(addButton.id);
   }

   function checkInput(btn1) {
      correctionID += 1;
      thisCorrection="correction" + correctionID.toString();
      var addButton=document.createElement("button");
      btn1.parentElement.appendChild(addButton) ;
      addButton.id=thisCorrection;
      addButton.innerHTML="Here is the new button";
      addButton.addEventListener ("dblclick",removeButton(addButton), false);
       };
   
&#13;
<div> <button onclick="checkInput(this)"><span style='background:yellow'>click to add button </span></button> </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是答案......(经过多次血,汗,泪和谷歌搜索!)

kp
  
   correctionID=0

   function removeButton(evt) {
         addButton=evt.target;
         console.log(evt.target.id);
         addButton.remove();  
         
   }

   function checkInput(btn1) {
      correctionID += 1;
      thisCorrection="correction" + correctionID.toString();
      var addButton=document.createElement("button");
      btn1.parentElement.appendChild(addButton) ;
      addButton.id=thisCorrection;
      addButton.innerHTML="Here is the new button";
      addButton.addEventListener("click",removeButton, false);
       };