一段时间后,我发现了以下javascript函数,它允许您动态地向表中添加一行:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
有没有人,实际上有javascript经验(因为我几乎没有)可以编写一个可以跳过<th>
标签的修复程序?
这是我不想受影响的表格的一部分:
<table id="scheduler">
<tr>
<th scope="col">Engineer</th>
<th scope="col">Monday</th>
<th scope="col">Tuesday</th>
<th scope="col">Wednesday</th>
<th scope="col">Thursday</th>
<th scope="col">Friday</th>
<th scope="col">Saturday</th>
<th scope="col">Sunday</th>
</tr>
我的问题是,当我有<th>
个标签时,标题行最终会成为“克隆”的行,而不是只包含<td>
个标记的行。
答案 0 :(得分:1)
只需更改该功能,即可指定要复制的行(给定从零开始的索引)。
addRow( "scheduler", 1 ); // to base it on the 2nd row
// give row number------v
function addRow(tableID, num) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
// -------------------------v
var colCount = table.rows[ num ].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
//-------------------------------v
newcell.innerHTML = table.rows[ num ].cells[i].innerHTML;
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
答案 1 :(得分:0)
试试这个:
function addRow(tableID){
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++)
{
var newcell = row.insertCell(i);
if(table.rows[0].cells[i].tagName != "th")
{
newcell.innerHTML = table.rows[0].cells[i].innerHTML; //alert(newcell.childNodes);
switch(newcell.childNodes[0].type)
{
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
else if(table.rows.length > 1 && table.rows[1].cells[i].tagName != "th")
{
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
switch(newcell.childNodes[0].type)
{
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}}