使用数据库中的Javascript使用图像填充div
我正在使用Firestore作为我的数据库,并希望用从中获得的详细信息填充我的HTML。 下面是填充我的HTML的连接和javascript方法:使用数据库中的Javascript使用图像填充div,javascript,html,css,image,google-cloud-firestore,Javascript,Html,Css,Image,Google Cloud Firestore,我正在使用Firestore作为我的数据库,并希望用从中获得的详细信息填充我的HTML。 下面是填充我的HTML的连接和javascript方法: db.collection("Ingredients2").where("Category", "==", 0).get().then(snapshot => { snapshot.forEach(doc => { //get database information const
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);
});
这会填充名称和价格,但不会显示图像。这是我的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;
}
你知道为什么图像没有显示吗?问题出在这里
var image1 = document.createElement("img" + id);
您正试图将id添加到本机createElement()方法,因此浏览器无法将其识别为图像元素,例如,浏览器希望类似于
标记的内容渲染图像,但它得到类似于
的内容,因此图像不会显示在未知标记中。你必须像这样创造它
var image1 = document.createElement("img");
如果要向任何元素添加id,可以像
var image1.id = id;
希望能有所帮助。问题出在这里
var image1 = document.createElement("img" + id);
您正试图将id添加到本机createElement()方法,因此浏览器无法将其识别为图像元素,例如,浏览器希望类似于
标记的内容渲染图像,但它得到类似于
的内容,因此图像不会显示在未知标记中。你必须像这样创造它
var image1 = document.createElement("img");
如果要向任何元素添加id,可以像
var image1.id = id;
希望能有帮助