首页 > 解决方案 > onEachFeature 函数内的传单嵌套 IF 条件

问题描述

我想根据条件语句设置我的弹出内容。我自己背后有两种方法,到目前为止,它们都没有奏效。

第一个:

 onEachFeature: function (pointFeature, layer) {
 function Stream() {
  if (pointFeature.properties.Stream = 1) {
    "<p> Live Stream </p>"
  } else { "<p> Image refresh </p>"}
  }
  var popupContent = "<p><h2 class='webcam_location'>" +
    pointFeature.properties.Location + "</h2></p>" + 
    "<h4 class='webcam_provider'>" + pointFeature.properties.Provider + "</h4>" +
    "<iframe src='" + pointFeature.properties.Link + "' height='200' width='300' title='camera 
    thumbnail'></iframe>" +
      Stream()
      };
     layer.bindPopup(popupContent);
    }

第二个:

  onEachFeature: function (pointFeature, layer) {
   var popupContent = "<p><h2 class='webcam_location'>" +
    pointFeature.properties.Location + "</h2></p>" + 
    "<h4 class='webcam_provider'>" + pointFeature.properties.Provider + "</h4>" +
    "<iframe src='" + pointFeature.properties.Link + "' height='200' width='300' title='camera 
    thumbnail'></iframe>" +
      if (pointFeature.properties.Stream = 1) {
        "<p> Live Stream </p>"
      } else { "<p> Image refresh </p>"}
      };
    layer.bindPopup(popupContent);

控制台出现错误:

SyntaxError:意外的标记“如果”

如何将 if 语句放在现有函数中?

标签: javascriptleaflet

解决方案


用模板文字语法替换串联,并为您的条件文本使用单独的串联。

像这样:

更新:根据您的评论,我已经修改了解决方案以更接近您提供的小提琴。

这应该足够接近您以适应。

首先,将弹出内容和条件内容保存到变量中。使用所需的变量构建字符串,包括条件内容。然后使用该单个变量 ( popUpContent) 作为要添加到弹出窗口的内容。

onEachFeature: function(pointFeature, layer) {
  const stream = pointFeature.properties.Stream;
  let popUpConditionalContent;

  if (stream === 1) {
    popUpConditionalContent = "<p class='webcam_refresh'> Live Stream </p>"
  } else {
    popUpConditionalContent = "<p class='webcam_refresh'> Image refresh </p>"
  }

  const popUpContent = `<p><h2 class='webcam_location'>
    ${pointFeature.properties.Location}</h2></p>
    <h4 class='webcam_provider'>${pointFeature.properties.Provider}</h4>
    <iframe src='${pointFeature.properties.Link}' height='200' width='300' title='camera 
  thumbnail '></iframe>${popUpConditionalContent}<b class='popup_category'>Rotation:</b>${pointFeature.properties.Rotation}${stream}`;

  var popUp = L.popup({
    className: 'map-popup',
  }).setContent(popUpContent);

  layer.bindPopup(popUp);
}

推荐阅读