[英]jQuery append is not parsing HTML tags
It seems like many people have had this problem in the past but none of the solutions work for me.过去似乎很多人都遇到过这个问题,但没有一个解决方案对我有用。
I have a method that is firing after receiving a response from a POST request:我有一个在收到 POST 请求的响应后触发的方法:
xhr.onload=function(e) {
if(this.readyState === 4) {
res = JSON.parse(e.target.responseText);
var userHtml = '<p class="userText"><span>' + res.userText + "</span></p>";
document.getElementById("chatbox").append(userHtml);
var botHtml = '<p class="botText"><span>' + res.botText + "</span></p>";
document.getElementById("chatbox").append(botHtml);
document
.getElementById("userInput")
.scrollIntoView({ block: "start", behavior: "smooth" });
}
};
Inside a "chat bot", this is supposed to render a text bubble on the right (for the userText
) and a text bubble on the left (for the botText
).在“聊天机器人”内,这应该在右侧呈现一个文本气泡(对于userText
),在左侧呈现一个文本气泡(对于botText
)。 However, when this method triggers, it just appends the raw HTML into the chatbox, as so:但是,当此方法触发时,它只是将原始 HTML 附加到聊天框中,如下所示:
<p class="userText"><span>Hi, how are you.</span></p><p class="botText"><span>I'm fine thanks, how are you?</span></p>
Is there a way I can fix this?有没有办法解决这个问题?
Thanks!谢谢!
You need to use jQuery
/ append()
function not document.getElementById
您需要使用jQuery
/ append()
function 而不是document.getElementById
I have added both methods
below and you can see that $('#chatbox')
is parsing the HTML
while document.getElementById
is displaying out as a plain HTML
/ (raw) text
我在下面添加了这两种methods
,您可以看到$('#chatbox')
正在解析HTML
而document.getElementById
显示为纯HTML
/(原始) text
Live Demo:现场演示:
var res = { userText: 'bar', botText: 'foo' } var userHtml = '<p class="userText"><span>' + res.userText + "</span></p>"; document.getElementById("chatbox").append(userHtml); $('#chatbox').append(userHtml) var botHtml = '<p class="botText"><span>' + res.botText + "</span></p>"; document.getElementById("chatbox").append(botHtml); $('#chatbox').append(botHtml)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="chatbox"> </div>
Using document.getElementById
使用document.getElementById
If you are keen on using document.getElementById
then you need to use innerHTML
like this below.如果您热衷于使用document.getElementById
,那么您需要像下面这样使用innerHTML
。
Live Demo:现场演示:
var res = { userText: 'bar', botText: 'foo' } var userHtml = '<p class="userText"><span>' + res.userText + "</span></p>"; document.getElementById("chatbox").innerHTML += userHtml; var botHtml = '<p class="botText"><span>' + res.botText + "</span></p>"; document.getElementById("chatbox").innerHTML += botHtml;
<div id="chatbox"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.