0

测试页面

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>testcase</title>
</head>
<body>
    <button onclick="Foo()">Eat me</button>
    <button id="bar"><-- Hit it</button>
    <table id="testTable" onchange="Bar()"></table>

    <script type="text/javascript">
        function Foo(){
            var table = document.getElementById("testTable");
            for(var i=0; i < 7; i++){
                var row = document.createElement("tr");
                for(var j=0; j < 7; j++){
                    var cell = document.createElement("td");
                    cell.innerHTML = i + "-" + j;
                    row.appendChild(cell);
                }
                table.appendChild(row);
            }
            Bar();
        }
        function Bar(){
            var bar = document.getElementById("bar");
            var table = document.getElementById("testTable");
            if(bar.textContent){
                bar.textContent = "table.rows.length = " + table.rows.length;
            }else{
                bar.innerText = "table.rows.length = " + table.rows.length;
            }
        }
    </script>
</body>
</html>

在 Firefox 19, Chrome 26 或 IE9+ 上,后面的数字table.rows.length =是正确的,但是 IE8 总是0table.rows本身也是空的(我不知道如何证明,IE 的调试工具不会显示 Javascript 对象的内容Chrome 和 Firefox 会)。似乎 IE8 在计算动态生成表的行数时有问题:/

4

1 回答 1

0

你也可以这样做——

 <!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>testcase</title>
</head>
<body>
    <INPUT type="button" value="Add Row" onclick="addRow('testTable')" />    <button type="button" onclick="Bar()" id="bar">table.rows.length = 0</button>
    <table id="testTable">
</table>

    <script type="text/javascript">
        function addRow(tableID) {
 alert(tableID);
            var table = document.getElementById(tableID);
  for(var i=0; i < 7; i++){

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);


            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "checkbox";
            element1.name="chkbox[]";
            cell1.appendChild(element1);

            var cell2 = row.insertCell(1);
            cell2.innerHTML = rowCount + 1;

            var cell3 = row.insertCell(2);
            var element2 = document.createElement("input");
            element2.type = "text";
            element2.name = "txtbox[]";
            cell3.appendChild(element2);
}

        }
        function Bar(){
alert(document.getElementById("testTable").rows.length);

            var bar = document.getElementById("bar");
            var table = document.getElementById("testTable");
            if(bar.textContent){alert("sdsds");
                bar.textContent = "table.rows.length = " + table.rows.length;
            }else{
                bar.innerText = "table.rows.length = " + table.rows.length;
            }
        }
    </script>
</body>
</html>
于 2013-02-18T12:03:05.480 回答