0

我有这个 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" />';
    }
4

2 回答 2

1

更新的答案

回复您的评论:

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

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

如果数组包含markup,您不想创建任何类型的新节点。相反,分配给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

于 2012-05-13T07:10:32.137 回答
1

为了完整起见,如果您更喜欢使用 appendChild() 而不是 innerHTML 属性,这里有一些其他替代方案可以替代已接受的解决方案。

你也可以做到

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 及其功能。但是,这将需要重写您拥有的代码。

于 2012-05-13T07:45:49.407 回答