删除“;空”;带有if语句的传单弹出窗口中的属性

Remove "null" attributes in Leaflet popups with an if-statement

本文关键字:单弹出 属性 窗口 if 带有 删除 语句      更新时间:2023-09-26

我使用外部geojson属性来填充传单中的弹出窗口,如下所示:

function popUp (feature, geojson) {
var popupText=
"/*Name:*/" + feature.properties.name  + 
"/*Amount*/" + feature.properties.amounts;
geojson.bindPopup(popupText);
};

问题是:有些金额是"空"的。那么,我该如何编写if语句,以便如果金额为"null",那么字符串("amount")和属性("null")都不会显示在弹出窗口中?

您要查找的是一个条件语句:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

var popupText = '';
if (feature.properties.name) {
    popupText += '/*Name:*/' + feature.properties.name;
}
if (feature.properties.amount) {
    popupText += '/*Amount*/' + feature.properties.amount;
}
geojson.bindPopup(popupText);

或者使用条件三元运算符更短:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

var popupText = '';
popupText += (feature.properties.name) ? '/*Name:*/' + feature.properties.name : '';
popupText += (feature.properties.amount) ? '/*Amount*/' + feature.properties.amount : '';
geojson.bindPopup(popupText);