如何在Leaflet的onEachFeature函数中嵌套IF条件生成动态弹窗内容
错误原因分析
- 两种方案的共同错误:
if (pointFeature.properties.Stream = 1)中使用了赋值运算符=,而非比较运算符,会直接把Stream属性强制赋值为1,不会按预期做条件判断,需要改为===严格相等判断。 - 第一种方案错误:你定义的
Stream函数没有加return语句,执行后不会返回你写的HTML字符串,拼接到popupContent里的值会是undefined。 - 第二种方案错误:
if是流程控制语句,不能直接嵌入到字符串拼接的表达式中,因此触发语法错误。
正确实现方案
写法1:单独计算动态内容(可读性更高)
onEachFeature: function (pointFeature, layer) { // 先计算动态显示的内容 let streamText; if (pointFeature.properties.Stream === 1) { streamText = "<p> Live Stream </p>"; } else { streamText = "<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>" + streamText; layer.bindPopup(popupContent); }
写法2:三元运算符简化(适合简单判断场景)
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>" + (pointFeature.properties.Stream === 1 ? "<p> Live Stream </p>" : "<p> Image refresh </p>"); layer.bindPopup(popupContent); }
内容的提问来源于stack exchange,提问作者Geographos
相关产品推荐
相关产品推荐

