InnerHtml让我发疯了

时间:2015-11-07 21:27:29

标签: javascript html

要动态插入HTML代码,我们在选择标记后使用innerHTML。很简单,但对我来说不行。我已经在SO和互联网上看到了一些链接来做到这一点。

我的代码如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Javascript experiments</title>
  <link rel="stylesheet" type="text/css" href="assets/app_item.css"/>
  <!--script language="javascript" type="text/javascript" href="assets/inserting_items.js"></script-->
  <script language="javascript" type="text/javascript">
      function insert_items(how_much){
        for(var i=0; i < how_much; i++){
            var div_cont = document.getElementById("my_container");
            console.log(div_cont);
            div_cont.innerHtml = "<div class='desc_container'><span class='desc'>Some text</span></div>";
        }
     }
  </script>
  </head>
  <body>
  <header>
      <h3>Inserting code dynamically in webpage.</h3> 
  </header>
  <p>By pressing the button, it will insert items in webpage</p>
  <label>How much:</label>
  <input type="text" id="how_much"/>
  <input type="button" value="Submit" onclick="insert_items(document.getElementById('how_much').value)"/>
  <div id="my_container"></div>
  </body>
</html>

当我按下按钮时,什么也没发生。动态内容未添加到页面上。我在Firefox和Chrome上测试过。即使是最简单的div_cont.innerHtml = 'asdasd'也不会起作用。 这段代码很简单,但不起作用。这种行为有特定原因吗?

2 个答案:

答案 0 :(得分:2)

请注意.innerHTML

的大小写
div_cont.innerHTML = "<div class='desc_container'><span class='desc'>Some text</span></div>";

答案 1 :(得分:0)

应为div_cont.innerHTML = 'asdasd'

&#13;
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>Javascript experiments</title>
  <link rel="stylesheet" type="text/css" href="assets/app_item.css" />
  <!--script language="javascript" type="text/javascript" href="assets/inserting_items.js"></script-->
  <script language="javascript" type="text/javascript">
    function insert_items(how_much) {
      for (var i = 0; i < how_much; i++) {
        var div_cont = document.getElementById("my_container");
        console.log(div_cont);
        div_cont.innerHTML = "<div class='desc_container'><span class='desc'>Some text</span></div>";
      }
    }
  </script>
</head>

<body>
  <header>
    <h3>Inserting code dynamically in webpage.</h3> 
  </header>
  <p>By pressing the button, it will insert items in webpage</p>
  <label>How much:</label>
  <input type="text" id="how_much" />
  <input type="button" value="Submit" onclick="insert_items(document.getElementById('how_much').value)" />
  <div id="my_container"></div>
</body>

</html>
&#13;
&#13;
&#13;