javascript 手动给表增加数据的小例子

  先建一个页面如下:这里有两个表,上面一个有数据,下面一个没有数据,只有一个表头!

  

复制代码 代码如下:

  <body>

  <form id="form1" runat="server">

  <div>

  <table border='1px' width="500px" id="tables">

  <tr>

  <td>1</td><td><input type="text" value="20"  style="width:50px" /><input type="text" value="200"style="width:50px" /></td><td>我是中国人</td><td>好好学习</td><td><input type="button" id="but" value="新增" onclick="butd(this);" /></td>

  </tr>

  <tr>

  <td>2</td><td><input type="text" value="30"style="width:50px" /><input type="text" value="300"style="width:50px" /></td><td>我是中国人</td><td>好好学习</td><td><input type="button" id="Button1" value="新增" onclick="butd(this);" /></td>

  </tr>

  <tr>

  <td>3</td><td><input type="text" value="40" style="width:50px" /><input type="text" value="400" style="width:50px"/></td><td>我是中国人</td><td>好好学习</td><td><input type="button" id="Button2" value="新增" onclick="butd(this);" /></td>

  </tr>

  <tr>

  <td>4</td><td><input type="text" value="50" style="width:50px" /><input type="text" value="500"style="width:50px" /></td><td>我是中国人</td><td>好好学习</td><td><input type="button" id="Button3" value="新增" onclick="butd(this);" /></td>

  </tr>

  <tr>

  <td>5</td><td><input type="text" value="60" style="width:50px" /><input type="text" value="600"style="width:50px" /></td><td>我是中国人</td><td>好好学习</td><td><input type="button" id="Button4" value="新增" onclick="butd(this);" /></td>

  </tr>

  </table>

  </div>

  <div>

  <table border='1px' width="500px" id="table2">

  <tr><td>ID</td><td>年龄</td><td>金钱</td><td>名字</td></tr>

  </table>

  </div>

  </form>

  </body>

  现在点击新增按钮,把点中的当前行的数据动态的加到下面的TABLE中,javascipt代码如下:

  

复制代码 代码如下:

  <script type="text/javascript">

  function butd(rows) {

  var rows = rows.parentNode.parentNode.rowIndex    //找到当前选中的行

  var mytable = document.getElementById('tables');  //找到当前这个 table;

  var Romm_price = mytable.rows[rows].cells[0].innerText; //找到当前行的第一列的值

  var room_rows = mytable.rows[rows].cells[1].children[0].value; //找到当前行的第二列第一个文本框的值;

  var room_rows2 = mytable.rows[rows].cells[1].children[1].value; //找到当前行的第二列第二个文本框的值;

  var room_rows3 = mytable.rows[rows].cells[2].innerText; //找到当前行的第三列的值;

  //找到table2,并给table2新增一行

  var x = document.getElementById('table2').insertRow();

  x.align = "center";  //设置行样式

  var Romm_typename = x.insertCell(0);

  var txtDate = x.insertCell(1);

  var Guest_Type_ID = x.insertCell(2);

  var room_row = x.insertCell(3);

  Romm_typename.innerHTML = Romm_price;

  txtDate.innerHTML = room_rows;

  Guest_Type_ID.innerHTML = room_rows2;

  room_row.innerHTML = room_rows3;

  }

  </script>

  这个里面最重要的就是如何得到当前你点击是哪行,然后是如何手动的把当前行的数据加到table中!