将图像数组访问到动态表中

时间:2012-08-30 17:08:44

标签: javascript dom

我编写了一个脚本,需要用图像替换数组中的文本字符串,即1.jpg2.jpg3.jpg)。我似乎没有正确引用图像对象并且正在解析为字符串。

我想用代码替换代码中的这个位。 从:

["One", "Two", "Three", "Four"],
["Un", "Deux", "Trois", "Quatre"],
["eins", "zwet", "dret", "vier"]

要:

["<img src=\"1.jpg\"", "<img src=\"2.jpg\"", "<img src=\"3.jpg\"", "<img src=\"4.jpg\""],
["<img src=\"5.jpg\"", "<img src=\"6.jpg\"", "<img src=\"7.jpg\"", "<img src=\"8.jpg\""],
["<img src=\"9.jpg\"", "<img src=\"10.jpg\"", "<img src=\"11.jpg\"","<img src=\"12.jpg\""]

    //Author : Alexander Adu-Sarkodie
    //To be used with acknowledgement

    function createTable(data) {
        var table = document.createElement("table");
        table.style.border = "1px solid #ffcc33";
        var thead = document.createElement("thead");
        thead.style.padding = "5px";
        var tr = document.createElement("tr");
        for (var i = 0; i < data[0].length; i++) {
            var th = document.createElement("th");
            th.style.border = "2px solid #ff0000";
            var newText = document.createTextNode(data[0][i]);
            th.appendChild(newText);
            tr.appendChild(th);
        }
        thead.appendChild(tr);
        table.appendChild(thead);

        var tbody = document.createElement("tbody");
        for (var i = 1; i < data.length; i++) {
            var tr = document.createElement("tr");
            for (var j = 0; j < data[i].length; j++) {
                var td = document.createElement("td");
                td.style.padding = "5px";
                td.style.border = "2px solid #00ff00";
                var newText = document.createTextNode(data[i][j]);
                td.appendChild(newText);
                tr.appendChild(td);
            }
            tbody.appendChild(tr);
        }
        table.appendChild(tbody);
        return table;
    }

    window.onload = function () {
        var table = createTable([
    ["1", "2", "3", "4"],
    ["One", "Two", "Three", "Four"],
    ["Un", "Deux", "Trois", "Quatre"],
    ["eins", "zwet", "dret", "vier"]
    ]);
        document.body.appendChild(table)
    }

1 个答案:

答案 0 :(得分:0)

类似于this

var images = ["one", "two", "doesn't", "matter"];

for (var i = 0; i < images.length; ++i) {

    images[i] = "<img src=\"" + (i+1) + ".jpg\" />";

}

for (var i = 0; i < images.length; ++i) {

    alert(images[i]);

}​