使用cloneNode时的负rowIndex

时间:2015-10-12 15:55:34

标签: javascript html

我需要检索使用cloneNode动态创建的行中的rowIndex。在确定它发生了什么的同时,我认识到rowIndex在同一个浏览器(IE)上获得了肯定,但在另一台机器上运行。 任何想法,我在这里缺少什么? THX!

的jsfiddle: https://jsfiddle.net/sLxrL9pL/15/

CODE:

function cloneMe() {
  var howManyRows = 3;
  var table = window.document.getElementById("myTable");
  var row = window.document.getElementById("rowToClone");
  var clone;
    
  for (var i = 0; i < howManyRows; i++) {
    clone = row.cloneNode(true);
    //clone.id = "test" + i;
    table.appendChild(clone);
  }
}
<table id="myTable">
  <colgroup>
    <col>
    <col>
    <col>
    <col>
  </colgroup>
    
  <thead>
    <tr>
      <td name="A">A</td>
      <td name="B">B</td>
      <td name="C">C</td>
    </tr>
  </thead>
  <tbody id="mybody">
    <tr id="rowToClone">
      <td><input name="A"></td>
      <td><input name="B"></td>
      <td><input name="C" onclick="alert(this.parentNode.parentNode.rowIndex)"></td>
    </tr>
  </tbody>
</table>
            
<button id="btn" onClick="cloneMe()">Clone me</button>

1 个答案:

答案 0 :(得分:2)

您需要在表的tbody部分附加克隆节点。尝试:

<table id="myTable">
  <colgroup>
    <col>
    <col>
    <col>
    <col>
  </colgroup>

  <thead>
    <tr>
      <td name="A">A</td>
      <td name="B">B</td>
      <td name="C">C</td>
    </tr>
  </thead>
  <tbody id="mybody">
    <tr id="rowToClone">
      <td><input name="A"></td>
      <td><input name="B"></td>
      <td><input name="C" onclick="alert(this.parentNode.parentNode.rowIndex)"></td>
    </tr>
  </tbody>
</table>
        
<button id="btn" onClick="cloneMe()">Clone me</button>
        
<script type="text/javascript">
    
    function cloneMe() {
        var howManyRows = 3;
        var table = window.document.getElementById("myTable");
        var row = window.document.getElementById("rowToClone");
        var clone;
        var tbody = table.tBodies[0];//get the body 
        for (var i = 0; i < howManyRows; i++) {
            clone = row.cloneNode(true);
            var len = table.rows.length;
            //clone.id = "test" + i;
           
            tbody.appendChild(clone);//append to body
        }
    }
</script>