【问题标题】:Call a function outside onEachFeature leaflet在 onEachFeature 传单之外调用函数
【发布时间】:2020-05-05 11:03:24
【问题描述】:

我想在应用于每个国家层的 onEachFeature 之外调用一个函数。

我要声明的函数是 Leaflet 点击层上的弹出窗口(例如:如果法国层被点击,则调用函数 showflag 作为一个甜蜜警报弹出窗口

当我在 onEachFunction 中声明和定义它时,它与以下代码完美配合

$.getJSON("js/test/custom.geojson", function(data) {
    // Apply a popup event to each "Features" of the dataset
   L.geoJSON(data, {
        onEachFeature: function (feature, layer) {
            layer.on('click', function showFlag(){
                Swal.fire({
                    title: "You have selected",
                    icon: "info",
                    html: '<span class="flag-icon flag-icon-'+feature.properties.iso_a2.toLowerCase()+'"></span>'
                })
            });
        }
    }).addTo(map);
});

但是当我在代码之外定义它时,它不起作用。它会在脚本加载后显示第一次出现 GeoJSON 数据的警报,之后不会响应任何点击事件。

$.getJSON("js/test/custom.geojson", function(data) {
    // Apply a popup event to each "Features" of the dataset
   L.geoJSON(data, {
        onEachFeature: function (feature, layer) {
            layer.on('click', showFlag(feature.properties.iso_a2.toLowerCase()));
        }
    }).addTo(map);
});

function showFlag(flag) {
    Swal.fire({
        title: "You have selected",
        icon: "info",
        html: '<span class="flag-icon flag-icon-'+flag+'"></span>'
    })
}

我哪里做错了?

【问题讨论】:

    标签: javascript jquery leaflet geojson sweetalert2


    【解决方案1】:

    将您的代码更改为:

    $.getJSON("js/test/custom.geojson", function(data) {
        // Apply a popup event to each "Features" of the dataset
       L.geoJSON(data, {
            onEachFeature: function (feature, layer) {
                layer.on('click', showFlag);
            }
        }).addTo(map);
    });
    
    function showFlag(e) {
        var layer = e.target;
        var flag = layer.feature.properties.iso_a2.toLowerCase();
        Swal.fire({
            title: "You have selected",
            icon: "info",
            html: '<span class="flag-icon flag-icon-'+flag+'"></span>'
        })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 2021-03-06
      • 2018-04-26
      • 1970-01-01
      • 2021-08-19
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多