簡體   English   中英

使用Javascript動態添加html元素和事件處理程序

[英]Dynamically add html elements and event handlers by using Javascript

我在表單中添加了3個div元素,並為每個元素動態添加了事件處理程序。 應該彈出一條顯示該div ID的消息。 但是,無論我單擊哪個框,它都會彈出最后一個div的ID 10175。

任何輸入將不勝感激。

<html>
<head>
<style type="text/css">
  .empty
          {
            background-color: green;
          }
   .safebox
          {
        margin-left: auto;
        margin-right: 20px;
        margin-top: 20px;
        text-align: center;
        float: left;
        width: 60px;
        height: auto;
          }
</style>
 <script type="text/javascript">
    function ClickMe(elem){
        alert(elem.id);
    };

   window.onload=function(){
    var tempdiv = document.createElement('div');
    var text = document.createTextNode('0173');
    tempdiv.className='safebox empty';
    tempdiv.appendChild(text);
    tempdiv.setAttribute('id','10173');
    tempdiv.appendChild(text);
    document.getElementById('pagewarpper').appendChild(tempdiv);

    var currentdiv = document.getElementById('10173');
    if (currentdiv.addEventListener){
       currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
    }
    else {
      currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
    }

    var tempdiv = document.createElement('div');
    var text = document.createTextNode('0174');
    tempdiv.className='safebox empty';
    tempdiv.appendChild(text);
    tempdiv.setAttribute('id','10174');
    tempdiv.appendChild(text);
    document.getElementById('pagewarpper').appendChild(tempdiv);

    var currentdiv = document.getElementById('10174');
    if (currentdiv.addEventListener){
       currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
    }
    else {
      currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
    }

    var tempdiv = document.createElement('div');
    var text = document.createTextNode('0175');
    tempdiv.className='safebox empty';
    tempdiv.appendChild(text);
    tempdiv.setAttribute('id','10175');
    tempdiv.appendChild(text);
    document.getElementById('pagewarpper').appendChild(tempdiv);

    var currentdiv = document.getElementById('10175');
    if (currentdiv.addEventListener){
       currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
    }
    else {
      currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
    }
      }
     </script>
   </header>
  <body>
 <form>
 <div id="pagewarpper">
</div>
  </form>
 </body>

嘗試

ClickMe(this);

使用currentDiv,您將創建一個閉合,該閉合指向3 div的同一對象。 最后一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM