javascript - 从 html 弹出窗口中删除 null

标签 javascript html popup mapbox

我想格式化弹出窗口的内容,以便 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值看起来像这样:

enter image description here

我的目标是消除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, "") 

这会产生所需的结果,但格式是问题。

enter image description here

即使将 JSON 对象封装在 <pre> 中,它也无法在弹出窗口中很好地显示。标签,它产生:

enter image description here

我想知道是否有解决方案来格式化我的弹出窗口,使其看起来像第一个图像 - 但排除空值。如何才能做到这一点是 html通过列出所有属性元素( course1course2course3 等...) 而不产生一堆空 <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/

相关文章:

javascript - 如何使用 javascript 字典中的键查找值

html - 如何让div从下往上移动

jquery - 使用 jQuery 有条件地在 WordPress 中打开 Popup Maker 弹出窗口

html - 我想知道如何在数据列表项上应用 css。我想更改高度和字体大小

html - 如何使用css使div占据剩余高度?

Angular Material : How to position MatDialog relative to element?

image - 在 Emacs 的弹出菜单中显示图像

javascript - 如何阻止在 Postman 上发送 undefined variable ?

javascript - 发布 ASP.NET 网站

javascript - 在ReactJS中使用axios GET作为axios POST