使用if语句删除Leaflet弹出窗口中的“null”属性

时间:2015-12-02 23:53:21

标签: javascript if-statement popup leaflet

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

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

问题:某些金额为“空”。那么,如何编写if语句,以便如果金额为“null”,那么字符串(“Amount”)和属性(“null”)都不会出现在弹出窗口中?

1 个答案:

答案 0 :(得分:1)

您正在寻找的是条件陈述:

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