在 svelte 中单击 Leaflet 弹出窗口时更新变量值

Updating a variable value when Leaflet popup is clicked in svelte

我在 Leaflet 地图的弹出窗口中有 url。单击此 link 时,我想设置一个变量值。 下面是代码。我正在读取 plotArray 的值并将其添加到传单地图。单击“单击此处了解详细信息”时,它将指向其他组件“详细信息”。 问题是,当我点击 url 时,它没有设置值。

for (var b = 0; b < plotArray.length; b++) {
  //For each entry of plotArray, add it to the map
  let ColMark;
  let content = L.DomUtil.create("div", "myPopup");
  content.innerHTML = `X: ${plotArray[b].X}, Y: ${plotArray[b].Y}, ID:${plotArray[b].id16}
      <br> <a style="font-size: small" href="/Details">Click here for details</a>`;
  if (plotArray[b].Mode == "Anchor") {
    ColMark = greenIcon;
  } else {
    ColMark = orangeIcon;
  }
  L.marker([plotArray[b].X, plotArray[b].Y], { icon: ColMark })
    .addTo(layerGroup)
    .bindPopup(content)
    .openPopup();
  content.onclick = (e) => {
    SelectedID.set(plotArray.id16); //i want to set value of the SelectID to the ID available inside content meaning whichever the popup is selected
    e.preventDefault();
    navigate("/Details", { replace: true });
  };
}

对于点击弹框内的url时的图片,SelectedID值应设置为0x3f1a。

我该怎么做?

您有多个问题:

  1. SelectedID.set(plotArray.id16); 将永远无法工作,因为缺少索引,应该是 SelectedID.set(plotArray[b].id16);

  2. 内容元素上的点击侦听器仅对数组中的最后一个弹出窗口起作用。因为您有多个弹出窗口,每个弹出窗口都会打开并应用点击侦听器,但随后它将从 DOM 中删除,因为您打开了另一个弹出窗口。所以只有最后一个弹出窗口才会有监听器。

  3. 我不确定 SelectedID.set(plotArray.id16); 是否每次都使用正确的 ID,因为你在循环中并应用点击监听器。

因此将您的代码更改为以下内容:

for (var b = 0; b < plotArray.length; b++) {
      //For each entry of plotArray, add it to the map
      let ColMark;
      let content = L.DomUtil.create("div", "myPopup");
      content.innerHTML = `X: ${plotArray[b].X}, Y: ${plotArray[b].Y}, ID:${plotArray[b].id16}
      <br> <a style="font-size: small" href="/Details">Click here for details</a>`;
      if (plotArray[b].Mode == "Anchor") {
          ColMark = greenIcon;
      } else {
          ColMark = orangeIcon;
      }
      
      // In this listener we read out the current marker of the popup and get the id to create a click listener on the content.
      map.on('popupopen',(e)=>{
          var marker = e.popup._source;
          var id = marker.plotId;
          e.popup._content.onclick = (e) => {
              alert(id);
              /*
              SelectedID.set(id); //i want to set value of the SelectID to the ID available inside content meaning whichever the popup is selected
              e.preventDefault();
              navigate("/Details", { replace: true });
               */
          };
      });

      var marker = L.marker([plotArray[b].X, plotArray[b].Y], { icon: ColMark })
          .addTo(layerGroup)
          .bindPopup(content);
      // the id is now a property of the marker and can read out over the marker
      marker.plotId = plotArray[b].id16;
      // open the popup after .plotId is set, because else plotId is undefined in `popupopen` event
      marker.openPopup();
  }