<table border="1" id="myTable">
<tr><th>用户名</th><th>密码</th></tr>
</table>
<script>
var myTable=document.getElementById("myTable"); //报错说myTable为空或不为对象
var newRow=myTable.insertRow();
//newRow.style.background="#FF9999";这行设置底色不生效。var newCellA=newRow.insertCell();
var newCellB=newRow.insertCell();
newCellA.innerHTML="2312313";
newCellA.style.background="#FF9999";newCellA.innerHtml="Terry";
newCellB.innserHtml="1234";
</script>函數在加載table之後再運行,否則必然報錯

解决方案 »

  1.   

    如楼上所说,script放置位置的问题
    document.getElementById("myTable")对应的element必须实际存在了才能使用
      

  2.   

    但我把<script>块挪到table之后,代码没报错了,但也不生效,没有新生成一行。
      

  3.   

    <html>
    <head>
    <title></title>  
    </head>
    <body>
    <table border="1" id="myTable">
    <tr  style="background-color:"><th >用户名</th><th>密码</th></tr>
    </table>
    <script>
    var mytable=document.getElementById("myTable"); 
    var newRow=mytable.insertRow();
    newRow.style.backgroundColor="#FF9999";
    var newCellA=newRow.insertCell();
    var newCellB=newRow.insertCell();newCellA.innerHTML="Terry";
    newCellB.innerHTML="1234";
    </script>
    </body>
    </html>
      

  4.   

    1。避免变量名重复
    var mytable=document.getElementById("myTable"); 
    2。用style定义样式
    newRow.style.backgroundColor="#FF9999";
    3。innerHTML与innerHtml的作用不一样
    newCellB.innerHTML="1234";
      

  5.   

    脚本最好写到function里 在 body 的 onload()事件里调用即可实现同样的效果,而且可以保证在页面对象未加载完成之前,代码不会被执行这样子:
    <html>
     <head>
    <title></title>  <script>
    function addRow()
    {
    var myTable=document.getElementById("myTable"); //报错说myTable为空或不为对象
    var newRow=myTable.insertRow();
    newRow.style.backgroundColor="#FF9999"; //这行设置底色不生效。
    var newCellA=newRow.insertCell();
    var newCellB=newRow.insertCell();newCellA.innerText="Terry";
    newCellB.innserText="1234";
    }
    </script></head>
    <body onload=addRow()><table border="1" id="myTable">
    <tr><th>用户名</th><th>密码</th></tr>
    </table></body>
    </html>