不能在js中使用DOM

时间:2015-04-15 21:09:57

标签: javascript jquery html

我想使用DOM制作动态表。此代码无效。我收到此错误

  

未捕获的TypeError:无法读取属性' insertRow'为null

js

 var persons = [
       { name:"Jurij Gagarin", birth: "9 March 1934", death:"27 March 1968" },
       { name:"Albert Einstein", birth: "14 March 1879", death:"18 April 1955 " },
       { name:"Mahatma Gandhi", birth: "2 October 1869", death:"30 January 1948" },
       { name:"Whitney Houston", birth: "9 August 1963", death:"11  February 2012" },];    
    function init() {
        table = document.getElementById('personsTab');
        tableSize = persons.length;
        //personsTab
        for(var i = 0; i < tableSize; i++){
            var row = table.insertRow(i);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            cell1.innerHTML = persons[i].name;
            cell2.innerHTML = persons[i].birth;
            cell3.innerHTML = persons[i].death;
        }
    } 
    window.onload = init();

HTML

    <table id="personsTab"> 
    <tr>
        <th id="name"><span>Name<span></th>
        <th id="birth"><span>Birth<span></th>
        <th id="death"><span>Death<span></th>
    </tr>
</table>

3 个答案:

答案 0 :(得分:2)

您在加载之前调用该函数

    window.onload = function(){init();}

或者更清洁

    window.onload = init;

问题是你调用函数而不是传递它

答案 1 :(得分:2)

您应该更改window.onload = init();window.onload = init(没有括号),因为你实际上并不想调用该函数。您只想将函数的引用分配给window.onload事件

答案 2 :(得分:0)

我认为你有一个范围问题。因为您没有将表声明为var,所以它在for循环中不可见。

尝试

var table = document.getElementById('personsTab');