在多维数组中使用imgs

时间:2015-03-10 21:20:42

标签: javascript arrays

我正在尝试从多维数组加载图像但是我似乎无法显示图像。它们只显示为文本。

function cartoonsRndm(x) {
    var cartoon = new Array();
    cartoon[0] = {
        person: "Trixie",
        show: "my little pony",
        img: "img/trixie.jpg"
    };
    cartoon[1] = {
        person: "Sanic",
        show: "Sanic the hagehug",
        img: "img/sanic.png"
    };
    cartoon[2] = {
        person: "megaman",
        show: "blue bomber",
        img: "img/man.jpg"
    };
    var hero = cartoon[x]["person"] + " " + cartoon[x]["show"] + " " + cartoon[x][src = "img"]
    document.getElementById("answer").innerHTML = hero
}

2 个答案:

答案 0 :(得分:5)

您正在连接具有src值的字符串。您需要构建<img> HTML标记:

var hero = cartoon[x].person + " " + cartoon[x].show + " <img src='" + cartoon[x].img + "'>";
document.getElementById("answer").innerHTML = hero;

另请注意,cartoon[x]["person"]相当于cartoon[x].person但更短。

答案 1 :(得分:0)

可能像

document.getElementById("answer").innerHTML = '<img src="'+cartoon[0]['img']+'">';