gpt4 book ai didi

javascript - 在 onEachFeature 传单之外调用函数

转载 作者:行者123 更新时间:2023-12-02 20:50:48 25 4
gpt4 key购买 nike

我想调用应用于每个国家/地区图层的 onEachFeature 之外的函数。

我要声明的函数是Leaflet点击层上的PopUp(示例:如果单击France层,则调用函数showflag作为sweet-alert弹出窗口

当我在 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>'
})
}

我哪里做错了?

最佳答案

将代码更改为:

$.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>'
})
}

关于javascript - 在 onEachFeature 传单之外调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61611611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com