![](/img/trans.png)
[英]Insert multiple rows and columns to a table in html dynamically using javascript code
[英]Dynamically How to append more rows with columns into table using javascript
我想將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,....)。
謝謝
請參閱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()
該解決方案是否滿足您的需求?
table.innerHTML = new Array(4).join(
'<tr>' + new Array(4).join('<td><input type="text" /></td>') + '</tr>'
);
這是一個建議:
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
}
另一種嘗試:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.