为什么表的td node.appendChild不起作用?

时间:2012-05-13 07:08:23

标签: javascript html

我有这个JavaScript函数来创建一个包含图像单元格的表:

    function Draw(array) {
        // get the reference for the body
        var body = document.getElementsByTagName("body")[0];
        document.clear();

        // creates a <table> element and a <tbody> element
        var tbl = document.createElement("table");
        tbl.setAttribute("borderstyle", "1");
        var tblBody = document.createElement("tbody");

        // creating all cells
        for (var j = 0; j < 4; j++) {
            // creates a table row
            var row = document.createElement("tr");

            for (var i = 0; i < 4; i++) {
                // Create a <td> element and a text node, make the text
                // node the contents of the <td>, and put the <td> at
                // the end of the table row
                var cell = document.createElement("td");
                var cellText = document.createElement(array[4 * j + i]);
                cell.appendChild(cellText);
                row.appendChild(cell);
            }

            // add the row to the end of the table body
            tblBody.appendChild(row);
        }

        // put the <tbody> in the <table>
        tbl.appendChild(tblBody);
        // appends <table> into <body>
        body.appendChild(tbl);
        // sets the border attribute of tbl to 2;
        tbl.setAttribute("border", "2");
    }

但在

var cellText = document.createElement(array[4 * j + i]);
cell.appendChild(cellText);
row.appendChild(cell);

cell.appendChild(cellText);不起作用! 我不知道为什么,我不知道如何解决它!

更新 一个数组是这样的:

    var a = Array(16);
    for (var i = 0; i < 16; i++) {
        a[i] = '<img src="' + i + '.jpg" />';
    }

2 个答案:

答案 0 :(得分:1)

更新回答

重新评论:

  

它只是放了一个文字。这意味着我看到<img src ...的文字不是图像!

如果您告诉我们array[4 * j + i]包含标记(例如,在问题中包含了它的一个示例),那将非常有用。

如果数组包含标记,则不希望创建任何类型的新节点。而是分配给表格单元格的innerHTML

cell.innerHTML = array[4 * j + i];
row.appendChild(cell);

当您分配到innerHTML时,浏览器会解析标记并将相关内容添加到元素中。


在下面的评论之前和array的内容发布之前

原始答案

要创建文本节点,请使用createTextNode,而不是createElement。所以:

// Change here ---------v
var cellText = document.createTextNode(array[4 * j + i]);
cell.appendChild(cellText);
row.appendChild(cell);

假设array[4 * j + i]"Hi there"。您的document.createElement(array[4 * j + i])调用要求DOM创建一个标记名为Hi there元素,这与document.createElement('div')要求它创建带标记的元素的方式完全相同名称div

答案 1 :(得分:1)

为了完整起见,如果您更喜欢使用appendChild()而不是innerHTML属性,那么这里是accepted solution的其他替代方法。

你也可以完成

var a = Array(16);
for (var i = 0; i < 16; i++) {
    a[i] = document.createElement('img');
    a[i].setAttribute('src', i + '.jpg');
}

它也会奏效。此外,您可以创建一个Image对象:

var a = Array(16);
for (var i = 0; i < 16; i++) {
    a[i] = new Image();
    a[i].src = i + '.jpg';
}

并且appendChild应该仍然有效。

另一种可用但完全不同的方法是使用javascript框架,例如jQuery及其功能。但这需要重写你拥有的代码。