[英]Insert a variable into a template literal href tag
我正在嘗試使用從 AJAX 請求中提取的動態生成的變量在模板文字中設置href
標記,但似乎無法弄清楚。 當我單擊標記的元素時沒有任何反應,並且由於某種原因,當我檢查網頁上的元素時<a href/>
沒有出現。
這是我的代碼:
[...]
data.forEach(([cafeId, cafeName, cafeAddress]) => {
var myCol = $('<div id="col"></div>');
var myPanel = $(
`
<div class="card-group">
<div class="card card-block m-3 overflow-auto" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title venue-name" id=\"` + cafeName + `\"><a href="venue/\"` + cafeId + `\"></a></h5>
<h6 class="card-subtitle mb-2 text-muted venue-address"></h6>
<div class="dropdown">
<div class="venue-options" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></div>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton"><a id="share" class="dropdown-item" href="#">Share</a><a id="addToListNoModal" class="dropdown-item" href="#">Add to List</a></div>
</div>
</div>
</div>
</div>
`
);
[...]
這是一個JSFiddle: https://jsfiddle.net/50pwyfde/12/
<a>
元素中的引號數量錯誤。 你正在創造一些看起來像
<a href="venue/"cafeId">
額外的引號導致它解析錯誤之后的所有內容。
將整行更改為:
<h5 class="card-title venue-name" id="${cafeName}"><a href="venue/${cafeId}"></a></h5>
有一個雙引號太多了:
`<a href="venue/\"` + cafeId + `\"></a>`
它一定要是:
`<a href="venue/` + cafeId + `\"></a>`
此外,模板文字語法允許您嵌入變量而不是連接多個字符串。
喜歡:
`<a href="venue/${cafeId}"></a>`
查看有關模板文字的優秀文檔: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.