2011-01-14 33 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