Image from array没有被追加到

Image from array is not appended to <div> id

本文关键字:追加 from array Image      更新时间:2023-09-26
id。

我有一个图像数组,当内容页面加载。数组中的一张图片将被附加到<div> id中并显示。

var GameQuestion = ["A?", "B?", "C?"];
var GameAnswer = [
  ["lib/True.png", "lib/False.png"],
  ["lib/True.png", "lib/False.png"],
  ["lib/True.png", "lib/False.png"]
];
var answerList,
  random_Question;
random_Question = Math.floor(Math.random() * GameQuestion.length);
$("#question").html(GameQuestion[random_Question]);
answerList = GameAnswer[random_Question];
$("#Answer_1").html(answerList[0]);
$("#Answer_2").html(answerList[1]);
<!-- Original Question -->
<div id="question" style="position:absolute; z-index:6; top:750px; left:160px; margin:auto; color:#FFFFFF; font-size:30px; width:800px; text-align: center;"></div>
<!-- Answer-Original-Choice List -->
<div id="Answer_1" class="answerswers" style="position:absolute; z-index:6; top:1006px; left:224px; margin:auto; color:#FFFFFF; font-size:25px; width:750px;"></div>
<div id="Answer_2" class="answerswers" style="position:absolute; z-index:6; top:1186px; left:224px; margin:auto; color:#FFFFFF; font-size:25px; width:750px;"></div>

当内容页面加载时,我只能看到问题,但是,应该添加和显示图像的部分。它只显示文件的路径名。

因此,如果内容页加载问题:A?, 2 image id应加载并显示True &amp的图像;假的。然而,在这一点上,我只看到img id"Answer_1"answers"Answer_2"的"lib/True.png"answers"lib/False.png"的文件路径名称。

那么,哪里出了问题?因为我需要img id来显示图像,而不是显示文件路径名称。

请帮助。谢谢

您必须创建具有src属性的<img>。有几种方法可以做到这一点,其中创建HTML字符串是非常直接的一种:

$("#Answer_1").html("<img src='" + answerList[0] + "'/>")

这将创建一个类似"<img src='lib/False.png'/>"的字符串。jQuery的html方法将把它放在你的#Answer_1div中,浏览器将把它解析为HTML。

一个更好的方法可能是已经创建了<img>标签,只更新src属性。你的HTML应该像这样:

<div><img id="Answer_1" /></div>
与js:

$("#Answer_1").attr("src", answerList[0]);

现在,浏览器不必在每次执行此操作时都删除/注入新图像。

(注意图像不能在代码片段中工作)

var GameQuestion = ["A?", "B?", "C?"];
var GameAnswer = [
  ["lib/True.png", "lib/False.png"],
  ["lib/True.png", "lib/False.png"],
  ["lib/True.png", "lib/False.png"]
];
var answerList,
  random_Question;
random_Question = Math.floor(Math.random() * GameQuestion.length);
$("#question").html(GameQuestion[random_Question]);
answerList = GameAnswer[random_Question];
$("#Answer_1").html("<img src='" + answerList[0] + "'/>");
$("#Answer_2").html("<img src='" + answerList[1] + "'/>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Original Question -->
<div id="question" style="position:absolute; z-index:6; top:750px; left:160px; margin:auto; color:#FFFFFF; font-size:30px; width:800px; text-align: center;"></div>
<!-- Answer-Original-Choice List -->
<div id="Answer_1" class="answerswers" style="position:absolute; z-index:6; top:1006px; left:224px; margin:auto; color:#FFFFFF; font-size:25px; width:750px;"></div>
<div id="Answer_2" class="answerswers" style="position:absolute; z-index:6; top:1186px; left:224px; margin:auto; color:#FFFFFF; font-size:25px; width:750px;"></div>