我已創建了顛倒表的行和列的javascript函數。下面是代碼:getElementsByTagName(「td」)不會返回選定行的所有td子項
function rotate(){
var table = document.getElementById("table");
var newtable = document.createElement("table");
var tablebody = table.getElementsByTagName("tbody")[0];
var newtablebody = document.createElement("tbody");
newtable.appendChild(newtablebody);
var rows = tablebody.getElementsByTagName("tr");
var heads = tablebody.getElementsByTagName("th");
var i;
for(i = 0; i < rows.length; i++)
{
var cells = rows[i].getElementsByTagName("td");
var j;
for(j = 0; j < heads.length; j++)
{
if(newtablebody.getElementsByTagName("tr")[j] == undefined)
{
var newrow = document.createElement("tr");
newtablebody.appendChild(newrow);
}
if(cells[j] == undefined)
{
var newcell = document.createElement("td");
newtablebody.getElementsByTagName("tr")[j].appendChild(newcell);
}
else
{
var newcell = cells[j];
var nbspan = cells[j].getAttribute("colspan");
newcell.setAttribute("rowspan", nbspan);
newcell.setAttribute("colspan", 1);
newtablebody.getElementsByTagName("tr")[j].appendChild(newcell);
}
}
}
table.innerHTML = newtable.innerHTML;
};
的問題是,當我試圖讓與標籤名「TD」所有的孩子當前行,我得到了很多不確定的細胞,而我可以從控制檯日誌中看到這些單元格存在幷包含數據(我在日誌中顯示innerHTML)。
我真的迷路了,所以任何幫助,將不勝感激。謝謝!
你是否確定'table','tablebody'等等都是非空的? – birdoftheday
如果你在這裏放一些HTML,測試你的腳本會容易得多。 – John
是的,我已經用console.log(table.innerHTML)等來檢查幾次,以確保。 其實我知道他們是非空的,因爲一些孩子被檢索,但有些不是,這就是爲什麼我很困惑... –