0

我想将 3 行追加到具有 3 列的表中。我尝试了以下代码,但它不起作用。

html代码:

  <table width="50%" border="0" cellspacing="2" cellpadding="5" class="height">
    </table>    

javascript代码:

  var table=document.getElementsByClassName('height') ;
  //creating inputfield with attribute
  var newField=document.createElement('input');
  newField.setAttribute('type','text');
  //creating <td> 
  var newTd=document.createElement('td');
  //appending newField into td
  newTd.appendChild(newField);
  //creating <tr> element
  var newTr=document.createElement('tr');
  //appending 3 <td>(newTd) elements,but here 3 <td>'s are not appending
  newTr.appendChild(newTd);
  newTr.appendChild(newTd);
  newTr.appendChild(newTd);
  //the above code was not working,if it works I want to append 3 <tr> into <table>.

我不想使用外部库(jquery,....)。

谢谢

4

4 回答 4

0

这是一个建议:

var table = document.getElementsByClassName('height')[0]; //I added [0] here

for (var i = 0; i < 3; i++) {
    var newField = document.createElement('input');
    newField.setAttribute('type', 'text');
    var newTd = document.createElement('td');
    newTd.appendChild(newField);
    var newTr = document.createElement('tr');
    newTr.appendChild(newTd);

    table.appendChild(newTr);  //you had forgoten this one
}

演示在这里

于 2013-10-12T13:52:49.687 回答
0

该解决方案是否适合您的需求?

table.innerHTML = new Array(4).join(
    '<tr>' + new Array(4).join('<td><input type="text" /></td>') + '</tr>'
);
于 2013-10-12T13:52:06.380 回答
0

请参阅http://coding.smashingmagazine.com/2013/10/06/inside-the-box-with-vanilla-javascript/并转到“API”部分。本页介绍了默认的 JS 表 DOM api。它由以下方法组成:

insertRow()
deleteRow()
insertCell()
deleteCell()
createCaption()
deleteCaption()
createTHead()
deleteTHead()
于 2013-10-12T13:44:44.910 回答
0

另一个尝试:

var table = document.getElementsByTagName('table')[0];
// creates a template row with 3 cells
var tr = document.createElement('tr');
tr.innerHTML = new Array(4).join(
  '<td><input type="text" /></td>'
);
// appends 3 rows to the table by cloning the template row
for (var i = 0; i < 3; i++) {
  table.appendChild(tr.cloneNode(true));
}
<table width="50%" border="0" cellspacing="2" cellpadding="5" class="height"></table>

于 2013-10-12T14:35:11.740 回答