javascript - 使用 Javascript 从数据库中填充图像到 div

标签 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 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 添加到 native createElement() 方法,因此浏览器无法将其识别为图像元素,例如浏览器期望类似的内容<img></img>标记来渲染图像,但它得到类似 <img123></img123> 的内容因此图像不会显示在未知标签中。你必须像这样创建它

    var image1 = document.createElement("img");

如果你想给任何元素添加id,你可以像这样单独添加

    var image1.id = id;

希望对你有帮助。

关于javascript - 使用 Javascript 从数据库中填充图像到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47234427/

相关文章:

css - 使用 CSS 在悬停时为圆形边框线设置动画

Internet Explorer 中的 Javascript 变量意外更改

javascript - 将对象加载到表单中

html - DIV 定位不起作用

html - 使用不同屏幕尺寸的 Canvas

javascript - 用于构建自动化的 Web UI 管道

css - 悬停在 div 上会影响外部元素

javascript - 将交互式 Flash 动画转换为 JavaScript 以在 html5 中使用

javascript - 如何添加带有动态更新图表的 map 弹出窗口

javascript - 如何用JS获取标记的文字