javascript - Appending HTML content via jQuery
问题描述
I have a page where I load comments on demand by using jQuery. I have <div id="comments">
where I append HTML by formatting a predefined template.
My template is as follows :
<div class="entry clearfix" style="position: absolute; left: 1oopx; top: 20px;">
<div class="comment-image">
<img class="image_fade" src="<#ImageUri#>" alt="<#Header#>">
</div>
<div class="entry-title">
<h2><a href="/Blog/Coments/<#Uri#>"><#Header#></a></h2>
</div>
<ul class="entry-meta clearfix">
<li><i class="icon-calendar3"></i> <#CommentDate#></li>
<li><i class="icon-user"> <#Handle#></i></li>
</ul>
<div class="entry-content">
<#Body#>
</div>
</div>
;
I use a jQuery GET to get comment content then I replace the content as follows :
html += blogitemHtml
.replace(/<#ImageUri#>/g, item.ImageUri)
.replace(/<#Header#>/g, item.Header)
.replace(/<#Uri#>/g, item.FriendlyUri)
.replace(/<#CommenDate#>/g, item.PublishedOn)
.replace(/<#Handle#>/g, item.Handle)
.replace(/<#Body#>/g, item.Intro);
$("#comments").append(html);
The problem is data in Body is also and HTML document with tags. So instead of a formatted text I see HTML tags instead.
I know I could use the jQuery html() function but it changes the content of the div, where I want to append new content.
How can I possibly add the content and displayed it in a formatted way as the HTML tags should.
Example I should see:
This is my first comment. And I would like to thank you with this video
Bu instead I see :
<p> This is my <b>first</b> comment. And I would like to thank you with this <a href="https://youtube.com">video</a>.
解决方案
尝试使用parseHTML()
将字符串解析为 DOM 节点数组。
var htmlNodes = $.parseHTML( html);
$("#comments").append(htmlNodes );
推荐阅读
- android - 无法按时间戳对 Firebase 实时数据库中的数据进行排序
- node.js - NodeJS + MongoDB - find().sort().toArray() 不起作用
- kubernetes - 您如何像 ECS 服务一样将服务帐户附加到 gke 部署/服务?
- python - OpenCV错误的关键点位置
- java - 是否可以在 Android 中以 dd-mm-yyyy 格式获取 Date 对象?
- python - 将以 n**x 形式给出的输入转换为整数
- r - 使用 scale_x_date 的日期格式给出错误
- javascript - 如何使用 node.js 和 ajax 和 mysql 处理异步编程中的方法?
- logging - 12因素记录到logstash的方式
- python - 创建一个进程,该进程创建一个再次更新全局变量的线程