2011-08-30 75 views
2

不工作我有一個表結構追加TR在表中IE

<table id="tableId"> 
<tbody id="tbodyId"> 

    <tr id="trId1"> 
    <td>id</td><td>name</td> 
    </tr> 

</tbody> 
</table> 

我加入新行簡單的JavaScript這樣的。

var itemsContainer = dojo.byId('tbodyId'); 
itemCount++; //it will give id to tr i.e. trId2 

var newItemNode = document.createElement('tr'); 
newItemNode.setAttribute("id", 'trId' + itemCount); 
newItemNode.innerHTML ='<td>id</td><td>anotherName</td>'; 

itemsContainer.appendChild(newItemNode); 

所有在Firefox中正常工作,但行不附加在IE中。在Firefox之後的新表格變成了。

<table id="tableId"> 
<tbody id="tbodyId"> 

    <tr id="trId1"> 
    <td>id</td><td>name</td> 
    </tr> 

    <tr id="trId2"> 
    <td>id</td><td>anotherName</td> 
    </tr> 

</tbody> 
</table> 

我看到了其他的代碼和幫助。我只需要一個簡單的JavaScript沒有jQuery的表中的一個tbody。

回答

2

有用於創建表格單元格(和行)特殊功能如 - 行和的insertCell對細胞的insertRow - 它工作在所有瀏覽器

var newItemNode = itemsContainer.insertRow(itemsContainer.rows.length - 1); 
newItemNode.setAttribute("id", 'trId' + itemCount); 

var cell = newItemNode.insertCell(0); 
cell.innerHTML = 'id'; 

...

PS。我認爲道場框架有一些用於插入行和單元格

+0

你是右行和的insertRow工程insertCel所有瀏覽器。 –

1

首先,this jsfiddle工作正常FF6 & IE8

確保你真正的HTML有適當的標記。您的示例示出了沒有斜線

<tr id="trId2"> 
    <td>id</td><td>anotherName</td> 
    </tr> 

<tbody> <!-- This line should be </tbody> --> 

IE是不一致的,其接受壞標記的閉合tbody元件。

此外,這樣的代碼:

var newItemNode = document.createElement('tr'); 
newItemNode.setAttribute("id", 'trId' + itemCount); 
newItemNode.innerHTML ='<td>id</td><td>anotherName</td>'; 

正是那種代碼工具包像道場(及其聰明的表妹,jQuery的)都建避免。我懷疑用於創建新行的代碼在您測試的IE版本中有所不同。

+0

在我的代碼中關閉。這是一個錯字。我檢查的代碼是一樣的。 –

1

試試這個

<html> 
<script language = "javascript"> 

function kk() 
{ 
    var itemsContainer = document.getElementById("tbodyId"); 

    var newItemNode = document.createElement('tr'); 
    newItemNode.setAttribute("id", 'trId' + 1); 
    var newCellItem1 = document.createElement('td'); 
    newCellItem1.innerHTML = "id"; 
    var newCellItem2 = document.createElement('td'); 
    newCellItem2.innerHTML = "anotherName"; 
    newItemNode.appendChild(newCellItem1); 
    newItemNode.appendChild(newCellItem2); 
    itemsContainer.appendChild(newItemNode); 

} 
</script> 
<table id="tableId"> 
<tbody id="tbodyId"> 

    <tr id="trId1"> 
    <td>id</td><td>name</td> 
    </tr> 


</tbody> 
</table> 
<input type="button" value = "heihei" onclick = "kk();"></input> 
</html>