我想将3行追加到3列的表中。我尝试了以下代码,但它没有用。
html代码:
<table width="50%" border="0" cellspacing="2" cellpadding="5" class="height">
</table>
javascriptcode:
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,....)。
感谢
答案 0 :(得分: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()
答案 1 :(得分:0)
此解决方案是否符合您的需求?
table.innerHTML = new Array(4).join(
'<tr>' + new Array(4).join('<td><input type="text" /></td>') + '</tr>'
);
答案 2 :(得分: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
}
答案 3 :(得分: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>