繁体   English   中英

将变量连接到 javaScript 中的 html 字符串

[英]concatenate a variable to a html string in javaScript

请对我温柔,这是我第一次将问题上传到堆栈溢出,并且由于我在编程方面相当新手,所以我可能在术语上有点模糊;-)

我的问题是我有一个 function ,它在 map 上放置了一些标记,这在我加载站点时会自动发生,这些标记不同并且包含不同的“奖杯”,我已将其放置在锁定到标记的弹出窗口中。 但是我希望程序能够收集奖杯,因此我想在我的 javaScript 文件中调用一个 function 作为我的参数,当我单击弹出窗口中的一个按钮时。

到目前为止,它看起来像这样:

    function createMarker(coords,trophy) {
      var id
      // check if array is empty and set id to 0 if it is
      if (markers.length < 1) id = 0
      // else make id based on array length
      else id = markers[markers.length - 1]._id + 1
      // custom popup content with HTML that can be styled
      var popupContent =
      '<div id= "divTrophy">'+
      '<img src=' + trophy +'></img>' +
      '<button onClick="trophyCollection('+trophy+')">Collect trophy</button>'+
      '<button onclick="closePopUp()">Close pop up</button>'+
      '</div>'
 '<button onClick="trophyCollection('+trophy+')">Collect trophy</button>'+

问题出在这一行,由于某种原因我不允许以这种方式连接,这让我感到困惑,因为它在<img>上面的行中运行良好。

我真的希望有人能帮助我,创造我在DK周围的小寻宝。

阿马利亚

尝试使用字符串插值。 像这样的东西。

`your_html_string ${your_dynamic_value} your_html_string`

您可以在此处找到有关插值的更多信息。 如何在不连接的情况下在 JavaScript 中的字符串中插入变量?

尝试 escaping 它们应该可以工作,例如

'<button onClick="trophyCollection(\''+trophy+'\')">Collect trophy</button>'+

正如建议的那样,您可以尝试模板文字

var popupContent = `<div id="divTrophy">
   <img src="${trophy}"/>
   <button onClick="trophyCollection('${trophy}')">Collect trophy</button>
   <button onclick="closePopUp()">Close pop up</button>
</div>`

请注意,由于trophy是一个字符串,您仍然需要将其用引号括起来。

您可以在反引号字符串中插入整个 HTML 并插入如下值:

let popupContent =
  `<div id= "divTrophy">
    <img src=${trophy}></img>
    <button onClick="trophyCollection(${trophy})">Collect trophy</button>
    <button onclick="closePopUp()">Close pop up</button>
  </div>`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM