图像不存在 在传单中显示默认图像弹出窗口

时间:2021-01-23 15:35:49

标签: javascript image leaflet popup

在 Leaflet 中,我在弹出窗口中有一个链接,可以打开一个带有相关图像的新窗口,如果图像丢失,它会冻结应用程序,以解决我创建一个同名默认图像的问题。问题是我必须为每个丢失的图像执行此操作,并且宁愿以某种方式使用默认图像(NoImage.jpg)而不是用空白图像将文件夹弄乱,当可能丢失数千个图像时,这将是一项糟糕的工作结束。搜索时我找到了这个小功能,但无法使用弹出功能实现。如何解决这个问题?查看在弹出窗口中放置图像的小缩略图并在缩略图上放置超链接,当图像丢失时,红色警报“Noimage”图像可能是最好的选择。不知何故,弹出窗口应该能够显示图像是否存在...

我选择并尝试实现的功能

function checkImage(src, good, error) {
  var img = new Image();
  img.onload = good;
  img.onerror = bad;
  img.src = src;
}
// Test to see if function worked ****
// checkImage(
 // "http://jsfiddle.net/img/logo.png",
 //function () { alert(this.src + " " + "good"); },
 //function () { alert("bad"); }
//);
// ********************************

我的弹出窗口

  onEachFeature: function (feature, layer) {
    var popupText = "";

    popupText += feature.properties.blId
      ? "<br>ID:\u00A0<b>" + feature.properties.blId
      : "";

    popupText += feature.properties.name
      ? "</b><br>Name:\u00A0<b>" + feature.properties.name
      : "";
    
// here I want to be able to show a default image
// if the "original" is missing ... (1)
    popupText += feature.properties.blId
      ? "</b><b>" +
        '<a href="/data/images/myimages/' +
        feature.properties.blId +
        '.jpg"' +
        'target="_blank"' +
        ">Show image in new window</a>"
      : "";

    layer.bindPopup(popupText, {
      closeButton: true,
      offset: L.point(0, -20),
    });
    layer.on("click", function () {
      layer.openPopup();
    });
  },

(1) 这是我尝试的,但没有成功,弹出窗口显示“未定义”

popupText += feature.properties.blId
  ? checkImage(
      "/data/images/myimages/" + feature.properties.blId + ".jpg",
      function () {
        return (
          "</b><b><a href" +
          this.src +
          'target="_blank"' +
          ">Show image in new window</a>"
        );
      },
      function () {
        return (
          "</b><b>" +
          '<a href="/data/images/myimages/NoImage.jpg"' +
          'target="_blank"' +
          ">Show image in new window</a>"
        );
      }
    )
  : "";

0 个答案:

没有答案