- 删除“link.className = 'active';” 在 onclick 功能之前。
- 将“if (map.hasLayer(layer))”语句更改为更类似于“else”语句(“layer”而不是“thelayer”并且只有一个“className”更改)。
片段:
link.href = '#';
// remove line that was here
link.innerHTML = name;
link.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
if (map.hasLayer(layer)) {
map.removeLayer(layer);
map.removeLayer(gridlayer);
// you had "thelayer", but it should be "layer":
map.legendControl.removeLegend(layer.getTileJSON().legend);
// change two lines that were here to the following:
this.className = '';
} else {
map.addLayer(layer);
map.addLayer(gridlayer);
this.className = 'active';
map.legendControl.addLegend(layer.getTileJSON().legend);
}
thelayer = layer;
};
很抱歉解释混乱,但你一次问了两个问题,这是我能想到的最干净的回答方式。