我想格式化弹出窗口的内容,以便 null
值被完全删除。此时,我的弹出窗口充满了 features.properties
大批。 properties
中有20个元素,并且根据查询的功能,其中许多值将是 null
。
var feature = features[0];
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(feature.geometry.coordinates)
.setHTML('<div><b>' + feature.properties.city + '</div></b>' + '<div>'
+ feature.properties.course1 + '</div>' + '<div>'+
feature.properties.course2 + '<div>' + feature.properties.course3 + '</div>')
.addTo(map);
此时,会弹出一个示例,其中包含一些 null
值看起来像这样:
我的目标是消除null
值,而不是在弹出窗口中显示它们。
到目前为止我已经尝试过 JSON.stringify
选项,而不是在单独的 <div>
中列出每个元素元素。
function replacer(key, value) {
// Filtering out properties
if (value === "null" || value === null) {
return undefined;
}
return value;
}
JSON.stringify(feature.properties, replacer, "\t").replace(/\"/g, "").replace(/,/g, "")
这会产生所需的结果,但格式是问题。
即使将 JSON 对象封装在 <pre>
中,它也无法在弹出窗口中很好地显示。标签,它产生:
我想知道是否有解决方案来格式化我的弹出窗口,使其看起来像第一个图像 - 但排除空值。如何才能做到这一点是 html
通过列出所有属性元素( course1
、 course2
、 course3
等...) 而不产生一堆空 <div>
是?
最佳答案
这是使用经典 Javascript 的一种方法:
var features = {
properties: {
city: "Salzburg",
course1: "DCLead",
course2: "null",
course3: null,
field_1: "Hello"
}
};
function htmlFromProps(props, exclude) {
var html = "";
var i = 0;
for (p in props) {
if (props[p] && props[p] != "null" && exclude.indexOf(p) === -1) {
html += "<div>" + (i === 0 ? "<strong>" : "");
html += props[p];
html += (i++ === 0 ? "</strong>" : "") + "</div>\n";
}
}
return html;
}
popup.innerHTML = htmlFromProps(features.properties, ["field_1"]);
#popup {
width: 80%
}
<textarea id="popup"></textarea>
通过调用 .setHTML(htmlFromProps(features.properties, []))
来使用它,其中第二个参数是要排除的字段数组。
关于javascript - 从 html 弹出窗口中删除 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41611817/