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

标签 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); 不起作用! 我不知道为什么,也不知道如何解决!

更新 a 数组是这样的:

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

最佳答案

更新答案

回复您的评论:

It just put a text. it means I see the text of <img src ... not the image!

如果您告诉我们 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 的元素.

关于javascript - 为什么表的 td node.appendChild 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10569935/

相关文章:

java - Selenium 网络驱动程序 : IE can't find radio buttons nor checkboxes for using click() on them

html - 将 HTML 内容渲染到 Google 电子表格

html - 为什么即使我赚了 margin ,我的按钮也不会移动?

javascript - 如何通过javascript向表单添加值?

javascript 评估用户提交的简单数学node.js

javascript : . css jquery 视频反转

javascript - jQuery 水平滚动动画不起作用

html - 如何从 URL 压缩图像?

html - 在水平行中放置 3 个无序列表

javascript - Jquery 延迟变化