InnerHTML属性不起作用

时间:2015-06-28 18:14:53

标签: javascript html

我使用下面的代码使用innerHTML属性动态地将一大块html添加到div。这是我的HTML代码:

 <body>
   <form>    
     <div id="date_in"><input type="date" name="arrival"/></div>
     <div id="dat_out"><input type="date" name="departure"/></div>
     <div id="submit"><input type="submit" value="Submit"/></div>
   </form>
 </body>

关闭正文标记后,我添加了以下JavaScript,

<script type"text/javascript">
  var inDate= document.getElementById("date_in");   
  var inCal= document.createElement("div");
  inCal.id="inCal";
  inDate.appendChild(inCal); 
  document.getElementById("inCal").innerHTML= '<div id="calHeading">
                   <span id="left">Left</span>
                   <spanid="yearMonth">curMonth curYear</span>
                   <span id="right">Right</span>
                 </div>
                 <div id="weeKDays">
                   <span>S</span>
                   <span>M</span>
                   <span>T</span>
                   <span>W</span>
                   <span>TH</span>
                   <span>F</span>
                   <span>SA</span>
                 </div>';
  </script>

我上面的代码,没有添加innerhtml标记,我可以在视图源中看到。这段代码可能有什么问题?

1 个答案:

答案 0 :(得分:0)

您的JavaScript中存在语法错误,因为该字符串位于多行上。这应该有效:

<body>
   <form>

     <div id="date_in"><input type="date" name="arrival"/></div>
     <div id="dat_out"><input type="date" name="departure"/></div>
     <div id="submit"><input type="submit" value="Submit"/></div>

  </form>
 </body>

 <script>
 var inDate= document.getElementById("date_in");
 var inCal= document.createElement("div");

  inCal.id="inCal";    
  inDate.appendChild(inCal);

  document.getElementById("inCal").innerHTML = [
 '<div id="calHeading">',
     '<span id="left">Left</span>',
     '<spanid="yearMonth">curMonth curYear</span>',
     '<span id="right">Right</span>',
 '</div>',
 '<div id="weeKDays">',
     '<span>S</span><span>M</span>',
     '<span>T</span><span>W</span>',
     '<span>TH</span><span>F</span>',
     '<span>SA</span>',
 '</div>'].join('\n');

 </script>