图片加载到一个<div>

时间:2019-01-09 01:51:53

标签: javascript jquery firebase firebase-realtime-database

我正在使用Firebase数据库和jQuery开发一个消息传递应用程序,但是我遇到了一个问题:图像总是进入一个<div>

1条带有1张图片的消息:

2条消息,每条消息有1张图片:

这是我的代码:

HTML

<div id="messages">

JavaScript + jQuery

var l = console.log;
function getSearch() {
  var result = {};
  if (location.search !== "") {
    const s = location.search.replace("?", "").split("&");
    for (var i = 0; i < s.length; i++) {
      result[s[i].split("=")[0]] = s[i].split("=")[1];
    }
    return result;
  } else {
    return null;
  }
}

function dicToArray(dic) {
  var array = [];
  for (var i = 0; i < Object.keys(dic).length - 1; i++) {
    array[i] = dic[i];
  }
  return array;
}

function arrayToDic(array) {
  var dic = {};
  for (var i = 0; i < array.length; i++) {
    dic[i] = array[i];
  }
  dic.length = array.length;
  return dic;
}

function deleteFromArray(array, no) {
  var newArray = [];
  for (var i = 0; i < array.length; i++) {
    if (i !== no) {
      newArray[newArray.length] = array[i];
    }
  }
  return newArray;
}


// Listen for Messages
firebase.database().ref("/conversations/" + getSearch().c + "/msgs").on("value", function(s) {
  l("Reached conversation messages.");
  firebase.database().ref("/user_ids").on("value", function(snapshot) {
    l("Reached user_ids");
    $("#messages").html("");
    l("#messages is empty");
    for (var i = 0; i < s.val().length; i++) {
      l("Reached message loop: message no. " + i);
      if (s.val()[i].sender === snapshot.val()[firebase.auth().currentUser.email.replace(/\./g, "_")]) {
        l("Sender was self.");
        l("Configuring messageDiv.");
        var messageDiv = $("<div></div>");
        messageDiv.addClass("message");
        messageDiv.addClass("self");
        messageDiv.attr("data-msg-no", i);
        l("Configuring optionsDiv.");
        //console.log(i);
        var optionsDiv = $("<div></div>");
        optionsDiv.addClass("options");
        l("Configuring deleteButton.");
        var deleteButton = $("<button></button>");
        deleteButton.addClass("delete");
        deleteButton.click(function() {

          // Get message number from data-msg-no
          var msgNo = parseInt($(this).parent().parent().attr("data-msg-no"));
          //console.log(msgNo);

          l("Button Clicked\n Deleting Message No. " + msgNo);

          // Get messages from Firebase
          firebase.database().ref("/conversations/" + getSearch().c + "/msgs").once("value", function(snapshot) {
            l("Got messages from firebase");
            // Convert dic to array
            var msgArray = dicToArray(snapshot.val());
            l("Converted dic to array");
            l(msgArray);

            // Remove message number
            var newArray = deleteFromArray(msgArray, msgNo);
            l("Removed message from array");
            l(newArray);

            // Convert array to dic
            var newMsgDic = arrayToDic(newArray);
            l("Converted array to dic");
            l(newMsgDic);

            // Set in Firebase
            firebase.database().ref("/conversations/" + getSearch().c + "/msgs").set(newMsgDic).then(function() {
              l("Set in Firebase Database");
            }).catch(function(error) {
              console.error("Firebase Error at Line 138:\n" + error.code + " - " + error.message);
            });;
          });
        });
        deleteButton.text("Delete");
        optionsDiv.append(deleteButton);
        l("Appended options div to delete button.");
        var text = s.val()[i].data;
        var height = 40;
        if (text.includes("\n")) {
          console.log(text.split("\n"));
          for (var i = 0; i < text.split(/\n/g).length - 1; i++) {
            height += 10;
          }
        }
        l("MessageDiv increased in height if it needed to. for \\n");
        if (text.includes("FILE:")) {
          l("The message is a file.");
          (function() {
            // Is File
            // File ID
            var fileId = text.replace("FILE:", "");
            l("fileId of file (to retrieve from Storage): " + fileId);
            // File from Firebase Storage
            var fileObject = firebase.storage().ref("/user_files/" + fileId);
            l("fileObject has been set");
            // Check if Image
            fileObject.getMetadata().then(function(metadata) {
              l("Reached metadata.");
              l(metadata);
              if (metadata.contentType.split("/")[0] === "image") {
                // Is an image
                l("File is an image.");
                l("Configuring <img>");

                // Create <img>
                var image = $("<img>");

                // Add 'image-attachment' class to <img>
                image.addClass("image-attachment");

                // Add to message div
                messageDiv.append(image);
                messageDiv.append(optionsDiv);

                // Get download url of image
                fileObject.getDownloadURL().then(function(URL) {
                  l("Reached download URL: " + URL);
                  // Set src of <img> to download url
                  image.prop("src", URL);
                });

                image.on("load", function() {
                  l("The image has loaded.");
                  // Add height to message div
                  messageDiv.height(messageDiv.height() + image.height());
                  l("MessageDiv increased in height if it needed to. for images.");
                });
              } else {
                // Is not an image
                l("It's not an image.");

                l("Configuring <a> download link.");

                // Create <a> element
                var link = $("<a></a>");

                // Add 'download-attachment' class to <a>
                link.addClass("download-attachment");

                // Get download url
                fileObject.getDownloadURL().then(function(URL) {
                  l("Reached download URL: " + URL);
                  // Add URL to 'href'
                  link.prop("href", URL);
                });

                // Add height to message div
                messageDiv.height(messageDiv.height() + 20);
                l("MessageDiv increased in height if it needed to. for download attachments.");

                // Add to message div
                messageDiv.append(link);
                messageDiv.append(optionsDiv);
              }
            });
          })();
        } else {
          messageDiv.append(text.replace(/\n/g, "<br>"));
          messageDiv.append(optionsDiv);
        }

        messageDiv.height(height);
        $("#messages").append(messageDiv);


      } else {
        var messageDiv = $("<div></div>");
        messageDiv.addClass("message");
        messageDiv.addClass("other");
        console.log(i);
        var text = s.val()[i].data;
        messageDiv.append(text);

        $("#messages").append(messageDiv);
      }
    }
  });
});

此代码中没有任何错误。一切正常。我只需要找到解决这个问题的方法。

干杯!

1 个答案:

答案 0 :(得分:0)

我应该创建一个<div>元素数组,然后将图像添加到其中。

var data = [{
    url: "https://firebasestorage.googleapis.com/v0/b/stuchatonline.appspot.com/o/user_files%2F5q9WB2s8ZiJH9el?alt=media&token=434e8df9-96d6-4d20-a744-7b09dc8da43e",
    type: "attachment",
    filetype: "file"
  },
  {
    url: "https://firebasestorage.googleapis.com/v0/b/stuchatonline.appspot.com/o/user_files%2FJyLgPjFMddb0NZp?alt=media&token=003d6dbb-3769-42e6-80b8-fd99955a7772",
    type: "attachment",
    filetype: "image"
  },
  {
    data: "Hello!",
    type: "message"
  }
];
var messageDivs = [];
for (var i = 0; i < data.length; i++) {
  messageDivs[i] = $("<div></div>");
}
for (var i = 0; i < data.length; i++) {
  if (data[i].type === "message") {
    messageDivs[i].text(data[i].data);
  } else if (data[i].type === "attachment") {
    if (data[i].filetype === "file") {
      var link = $("<a></a>");
      link.addClass("download-attachment");
      link.text("Download Attachment");
      link.prop("href", data[i].url);
      link.prop("download", true);
      messageDivs[i].append(link);
    } else if (data[i].filetype === "image") {
      var img = $("<img>");
      img.addClass("image-attachment");
      img.prop("src", data[i].url);
      img.prop("alt", data[i].url);
      messageDivs[i].append(img);
    }
  }
}
for (var i = 0; i < data.length; i++) {
  $("body").append(messageDivs[i]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body></body>