[英]Populate a div with an image using Javascript from database
I am using Firestore for my database and looking to populate my HTML with the details I receive from it. 我正在将Firestore用于数据库,并希望使用从数据库中接收到的详细信息填充HTML。 Below is the connection and javascript method that populates my HTML: 以下是填充我的HTML的连接和javascript方法:
db.collection("Ingredients2").where("Category", "==",
0).get().then(snapshot => {
snapshot.forEach(doc => {
//get database information
const price = doc.data().Price;
const name = doc.data().Name;
const id = doc.data().IngredientID;
const image = doc.data().Photo;
//create elements
var button = document.createElement("button");
button.className = "imgButton";
var divbunname = document.createElement("bunname" + id);
divbunname.className = "imgName";
var divbunimage = document.createElement("bunimage" + id);
divbunimage.className = "imgPicture";
var divbunprice = document.createElement("bunprice" + id);
divbunprice.className = "imgPrice";
var image1 = document.createElement("img" + id);
image1.className = "imgPicture img";
divbunprice.innerHTML = price;
divbunname.innerHTML = name;
image1.src = image;
document.getElementById("bunstab").appendChild(button);
button.appendChild(divbunname);
button.appendChild(divbunimage);
divbunimage.appendChild(image1);
button.appendChild(divbunprice);
});
})
.catch(err => {
console.log('Error getting documents', err);
});
This populates the name and price but the image does not appear. 这将填充名称和价格,但不会出现图像。 This is my css: 这是我的CSS:
.imgButton {
position: relative;
cursor: pointer;
border: none;
background-color: rgba(119, 119, 119, 0.541);
border-radius: 25px;
width: 120px;
height: 120px;
margin-left: 30px;
margin-top: 30px;
}
.imgName {}
.imgPicture {
width: 60px;
height: 60px;
background-size: 100%;
vertical-align: middle;
display: inline-block;
outline: pink solid;
float none;
}
.imgPicture img {
width: 100%;
height: 100%;
outline: green solid;
}
Any ideas on why the image is not showing? 关于为什么图片未显示的任何想法?
Here is the problem 这是问题所在
var image1 = document.createElement("img" + id);
you are trying to add id to a native createElement() method and hence browser doesn't recognize it as an image element, for example browser is expecting something like <img></img>
tag to render image but it getting something like <img123></img123>
so images are not showing up in an unknown tag. 您尝试将id添加到本机的createElement()方法中,因此浏览器无法将其识别为图像元素,例如,浏览器期望使用<img></img>
标签之类的图像来呈现图像,但是却获得诸如<img123></img123>
因此图像不会显示在未知标签中。 You have to create it like 您必须像创建它
var image1 = document.createElement("img");
if you want to add id to any element, you can add it separately like 如果要将id添加到任何元素,可以将其单独添加,例如
var image1.id = id;
hope it'll help. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.