[英]How do you display an image with a source attached to an object? The object (question) is selected randomly and images should change with them
I have an array of objects which are questions.我有一系列问题的对象。 This is for a random question quiz.这是一个随机问题测验。 Basically, when one question is randomly selected, I thought all of the attributes would go with it (if "called" correctly).基本上,当随机选择一个问题时,我认为所有属性都会随之而来(如果“调用”正确)。 I am not sure how to display the image from the object when the question text (q) displays.当问题文本 (q) 显示时,我不确定如何显示来自对象的图像。
const questionBank = [
{
q: "This is question 1's text",
options:['1','2','3','4', '5'],
answer:4,
imgURL: 'http://drive.google.com/uc?export=view&id=googleDriveId',
},
{
q: "question 2 will go here",
options:['7','6','4'],
answer:0,
imgURL: 'http://drive.google.com/uc?export=view&id=differentDriveId',
}
function getNewQuestion(){
const question = document.querySelector(".question");
//set question text
question.innerHTML = currentQuestion.q;
//add image to question
//document.querySelector('.question').appendChild(img); (attempted, did not work)
//var img = new Image(); (attempted, did not work)
//img = document.createElement("img"); (attempted, did not work)
//img.src = document.querySelector('.imgUrl'); (attempted, did not work)
I think that is all the relevant code.我认为这就是所有相关的代码。
You were on the right track with creating a new img element, if you take a look at this post, you need to create a new image element.您在创建新的 img 元素方面走在了正确的轨道上,如果您看一下这篇文章,您需要创建一个新的图像元素。
on your last line, instead set image.src = currentQuestion.imgURL
as you want the current questions imgURL property, then you can appendChild() your new image element!在你的最后一行,设置image.src = currentQuestion.imgURL
作为你想要的当前问题 imgURL 属性,然后你可以appendChild()你的新图像元素!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.