javascript - 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 语句放在现有函数中?
解决方案
用模板文字语法替换串联,并为您的条件文本使用单独的串联。
像这样:
更新:根据您的评论,我已经修改了解决方案以更接近您提供的小提琴。
这应该足够接近您以适应。
首先,将弹出内容和条件内容保存到变量中。使用所需的变量构建字符串,包括条件内容。然后使用该单个变量 ( 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);
}
推荐阅读
- r - 在 R 中将字符串变量(例如“815”)重新编码为时间变量(08:15)
- flutter - 收到用户输入后,我的 setState 不刷新。我正在尝试建立一个聊天页面
- php - 为什么我的删除按钮在 PHP 中不起作用?
- python - 提高 Pandas 转换过程的效率
- javascript - 如何在 react-native 中将高度设置为 100%?
- java - CodingBat starOut,为什么使用子字符串不能正常工作
- kubernetes - 将本地文件复制到 aks 高级或标准存储
- python - 用 CSV 文件中的文本和整数值为汽车数据训练价格预测机器学习模型的最佳方法是什么?
- react-native - 使用 react-native-svg 时执行 UI 块时引发异常
- select - PySpark DataFrame 何时使用/不使用 Select