2011-01-14 34 views
0

在XHTML頁面我有這個div:問題的innerXhtml和onclick屬性

<div id="listAzioni"> 
    <h4 style="margin-bottom:3px;">List shape :</h4> 
</div> 

在div使用庫innerXhtml通過javascript輸入元件內隨後併入。

var paper = document.getElementById("listAzioni"); 
var toWrite = "<h4 style=\"margin-bottom:3px\">List shape :</h4>"; 
toWrite += "<input type=\"button\" class=\"listButton\" value=\""+id+"\" onclick=\"showAction('"+id+"');\"/>"+'<br/>'; 
innerXHTML(paper,toWrite); 

但添加輸入元素後沒有onclick屬性。我很努力地嘗試,但是我還沒有找到任何能解決我的問題的東西。我在哪裏做錯了?

回答

0

你試過了哪些瀏覽器?

我建議你使用標準的DOM API,我下面寫代碼:

<html> 
    <head> 
    <style type="text/css"> 
    .button { 
     border: 1px solid black; 
     padding: 3px; 
    } 
    </style> 
    <script type='text/javascript'> 
     function addButton() { 
     var container = document.getElementById('container'); 
     if (container != null && container != undefined) { 
      var child = document.createElement("div"); 
      var button = document.createElement("input"); 

      button.value = "Click to alert"; 
      button.type = "button"; 
      child.style.padding = "10px"; 
      child.style.border = "2px solid red";  
      button.className = "button"; 

      button.onclick = showAlert; 
      child.appendChild(button); 
      container.appendChild(child); 
     } 
     } 

     function showAlert() { 
     alert("you clicked the button!"); 
     } 
    </script> 
    </head> 
    <body> 
    <div id="container"></div> 

    <input value="add div and button" type='button' onclick='addButton();'/> 
    </body> 
</html> 
+0

我想我在FF和Chrome的代碼,但兩者給我這個錯誤。我也認爲我有你的替代方案,但我嘗試運行當前代碼而不更改任何內容。 – LuckyStarr 2011-01-14 13:05:01