日期:2014-05-16  浏览次数:20371 次

cloneNode的问题
JS新手,想做一个动态增删Table,使用cloneNode()方法复制上一行的tr节点,但是结果是将所有的tr节点都复制了,这是为什么啊?从FireBug上面观察FF浏览器在外面都增加了的<tobdy>,但是IE6中测试也是复制了两行(IE7+没有测试 因为工作原因需要使用ie6)。另外请教下动态操作Table都是使用HTML DOM 的table对象吗?
HTML code

<html>
<body>
    <table id = "tab1" border = 1>
        <tr>
            <td><input type="text" /></td>
            <td>b</td>
            <td>c</td>
            <td>d</td>
            <td>e</td>
        </tr>
        <tr>
            <td><input type="text" /></td>
            <td>b</td>
            <td>c</td>
            <td>d</td>
            <td>e</td>
        </tr>
    </table>
<button onClick="addRow()">添加行</button> <button onClick="deleteRow()">删除行</button>

<script type="text/javascript">

    function addRow()
        {    
            var theTable = document.getElementById("tab1");
            newrow = theTable.lastChild.cloneNode(true); //复制最后一行
            theTable.appendChild(newrow);  //插入
        }
    function deleteRow()
        {        
            var theTable = document.getElementById("tab1");
            var totalRow = theTable.childNodes.length;
            if (navigator.userAgent.indexOf("MSIE") == -1 ) //如果不是ie  总行数减1
                totalColume = totalRow-1;
                if (totalColume > 1 )
                {    
    //                alert(totalRowume);
                    theTable.removeChild(theTable.lastChild);
                }
        }
</script>
</html>


------解决方案--------------------
theTable.getElementsByTagName('tr')[1].cloneNode(true);
------解决方案--------------------
或者:

theTable.rows[theTable.rows.length-1].cloneNode(true);