我正在建立一個聊天室,需要div通過 javascript在一系列中添加我的聊天訊息。div 結構如下所示:
<div class="main-friend-chat" id="chat-log">
<div class="media chat-messages">
<div class="media-body chat-menu-content">
<div class="">
<p class="chat-cont">My message should go here! Will you tell me something</p>
<p class="chat-cont">about yours?</p>
</div>
</div>
</div>
</div>
我需要在<p>標簽中添加文本。到目前為止,我設法只動態創建了一個 div。當我嘗試構建第二個時,div我得到并出錯 Saying ' append' is not a function。我的 JS 代碼如下所示:
const data = JSON.parse(e.data);
var newNode = document.createElement('div');
newNode.className = 'media chat-messages';
var newNode2 = document.createElement('div');
newNode2.className = 'media-body chat-menu-content';
newNode2.innerHTML = (data.message "\n") ;
document.getElementsByClassName("newNode").appendChild(newNode2);
document.getElementById('chat-log').appendChild(newNode);
我將不勝感激有人可以教我如何做到這一點嗎?
uj5u.com熱心網友回復:
你的一行說[倒數第二行]
document.getElementsByClassName("newNode").appendChild(newNode2);
我看不到任何此類名為 "newNode" 的元素。這意味著您正在對未定義的內容呼叫 append 方法。我認為這似乎是問題所在,否則代碼看起來沒問題
uj5u.com熱心網友回復:
var newNode = document.querySelector('#chat-log')
var input = document.getElementById("chat-input");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
var htmlString = ` <div >
<div >
<div ><p >`
htmlString = event.target.value
htmlString = ` </p></div>
</div>
</div>`
const placeholder = document.createElement('div');
placeholder.innerHTML = htmlString;
const node = placeholder.firstElementChild;
newNode.appendChild(node)
event.target.value = ''
}
});
<input id="chat-input">
<div class="main-friend-chat" id="chat-log">
<div class="media chat-messages">
<div class="media-body chat-menu-content">
<div class="newNode">
<p class="chat-cont">My message should go here! Will you tell me something</p>
<p class="chat-cont">about yours?</p>
</div>
</div>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/366024.html
標籤:javascript 查询
下一篇:根據輸入替換div中的特定符號
