如何将变量作为 href 和变量文本放入其中? (Google 地图信息 window)

How to put a variable as a href and variable text inside it? (Google maps info window)

我无法弄清楚如何在我的 google 地图信息 window 中放置动态链接,以及如何用标签包装一些动态文本。

如何将 lurl 传递给 a href,然后放置 placeResultStringArray[0]+","+placeResultStringArray[1]+","+placeResultStringArray[2]+ 在标签内?

这是我正在使用的代码:

function showDetails(placeResult, marker, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    let placeInfowindow = new google.maps.InfoWindow();
    let rating = "None";
    if (placeResult.rating) rating = placeResult.rating;
    let placeResultStringArray = placeResult.formatted_address.split(",");
    let lurl = `https://bajablast.live/${placeResultStringArray[0]}`;
    placeInfowindow.setContent(
      "<div><strong>" +
        placeResult.name +
        "</strong><br>" + 
        <a href = ${lurl}> +
        placeResultStringArray[0]+","+placeResultStringArray[1]+","+placeResultStringArray[2]+
        </a> +
        "<br>" +
        "Rating: " +
        rating +
        "</div>"
    );
    placeInfowindow.open(marker.map, marker);
    currentInfoWindow.close();
    currentInfoWindow = placeInfowindow;
    // showPanel(placeResult);
  } else {
    console.log("showDetails failed: " + status);
  }
}

替换

<a href = ${lurl}> +

`<a href="${lurl}">` +

...或与

"<a href=\"" + lurl + "\">" + 

...或与

"<a href='" + lurl + "'>" + 

您还需要将 </a> 括在引号中,因为您希望将其解析为字符串,而不是 javascript 表达式(这会导致错误)。

直到您可以轻松找出字符串连接的输出,找出错误的最简单方法是 console.log() 当前值并修改您的代码,直到记录的字符串是想要的结果。

很可能,您的 setContent 应该如下所示:

placeInfowindow.setContent(
  "<div><strong>" +
  placeResult.name +
  "</strong><br>" + 
  `<a href="${lurl}">` +
  placeResultStringArray[0] + 
  "," + 
  placeResultStringArray[1] +
  "," + 
  placeResultStringArray[2] +
  "</a>" +
  "<br>" +
  "Rating: " +
  rating +
  "</div>"
);

我会写成:

placeInfowindow.setContent(`
<div>
  <strong>
    ${placeResult.name}
  </strong>
  <br>
  <a href="${lurl}">
    ${[0,1,2].map(i => placeResultStringArray[i]).join(',')}
  </a>
  <br>
  Rating: ${rating}
</div>
`);

我发现 read/understand 更容易,因此修改。