【问题标题】:Populate a div with an image using Javascript from database使用数据库中的 Javascript 使用图像填充 div
【发布时间】:2017-11-11 04:41:57
【问题描述】:

我正在为我的数据库使用 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;
}

关于为什么图片没有显示的任何想法?

【问题讨论】:

    标签: javascript html css image google-cloud-firestore


    【解决方案1】:

    问题来了

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

    您正在尝试将 id 添加到本机 createElement() 方法中,因此浏览器无法将其识别为图像元素,例如浏览器期望类似<img></img> 标签来渲染图像,但它得到类似<img123></img123> 的东西,所以图像不会出现在未知标签中。您必须像

    一样创建它
        var image1 = document.createElement("img");
    

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

        var image1.id = id;
    

    希望它会有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2014-10-22
      • 1970-01-01
      相关资源
      最近更新 更多