[英]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.