[英]How to achieve string interpolation while appending html inside a div using Javascript
可能是一個愚蠢的問題,但就是這樣。 我試圖根據從我的支持 java 控制器接收到的數據在我的 div 中插入一些 html。 一切正常,但我不知道如何將收到的數據中的字符串插入到我的 jsp 的段落標記中。
這是代碼
<script>
$(document).ready(function() {
var url = "${context}/support/ajax";
$.ajax({
type : 'GET',
url : url,
dataType : 'json',
success : function(data, status, xhr) {
data.forEach(function(data) {
if (data.userType == 'O') {
$( ".chats" ).append(`
<div class='chat-avatar'>
<a class='avatar' data-toggle='tooltip' href='#'
data-placement='right' title='' data-original-title=''> <img
src='<c:url value = '/app-assets/images/portrait/small/avatar-s-1.png'/>'
alt='avatar'>
</a>
</div>
<div class='chat-body'>
<div class='chat-content'>
<p>{data.comment}</p> // **This is what I want to achieve**
</div>
</div>
`);
}
});
}
});
});
</script>
上面的 ajax 調用工作正常,我確實收到了數據。 此外,我可以將此 html 插入到適當的 div 元素中。 現在我想在 p 元素中插入 data.comment 值。
我該怎么做呢 ?
編輯--1
使用`${expression}` 語法后, <p>
標記在瀏覽器控制台中顯示為空白,而該值顯然存在。
編輯--2
我不知道為什么,但是"<p>"+d.comment+"</p>"
正在工作。 但不是插值。
因為您使用的是反引號 (`),所以您幾乎可以使用模板字符串。 您只需要正確使用占位符:
const data = {comment: 'The comment'}; const result = `...<p>${ data.comment }</p>...`; console.log(result);
我可以看到您將數據變量用於 ajax 響應和循環中數據的當前值。 您確定要引用正確的對象嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.