开发者

Problem with innerXhtml and onclick attribute

开发者 https://www.devze.com 2023-02-04 21:51 出处:网络
In the XHTML page i have this div: <div id=\"listAzioni\"> <h4 style=\"margin-bottom:3px;\">List shape :</h4>

In the XHTML page i have this div:

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

Subsequently incorporated within the div an input element via javascript using the library innerXhtml.

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);

But after adding the input element has no onclick att开发者_JS百科ribute. I tried so hard but I have not found anything that would solve my problem. Where am I doing wrong?


Which browsers have you tried?

I suggest you to use standard DOM APIs, I write your code as below:

<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

精彩评论

暂无评论...
验证码 换一张
取 消