Remove “null” attributes in Leaflet popups with an if-statement

三世轮回 提交于 2019-12-11 15:24:03

问题


I am using external geojson attributes to fill my popup windows in Leaflet, like this:

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

The problem: some of the amounts are "null". So, how do I write an if statement, so that if an amount is "null" then both the string ("Amount") and the attribute ("null") don't show up in the popup?


回答1:


What you are looking for is a conditional statement:

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);

Or even shorter using a conditional ternary operator:

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);


来源:https://stackoverflow.com/questions/34055382/remove-null-attributes-in-leaflet-popups-with-an-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!