如何使用Javascript呈现HTML字符串? [英] How to render HTML in string with Javascript?
问题描述
我有以下javascript代码:
I have the following javascript code:
var html = '<div class="col-lg-4 col-references" idreference="'+response+'"><span class="optionsRefer"><i class="glyphicon glyphicon-remove delRefer" style="color:red; cursor:pointer;" data-toggle="modal" data-target="#modalDel"></i><i class="glyphicon glyphicon-pencil editRefer" data-toggle="modal" data-target="#modalRefer" style="cursor:pointer;"></i></span><div id="contentRefer'+response+'">'+refer_summary+'</div><span id="nameRefer'+response+'">'+refer_name+'</span></div>';
$("#references").append(html);
此代码运行时, refer_summary
变量实际上包含一个字符串,该字符串可能包含HTML标记,例如< b>
,< i>
等,但是,这些标记会显示在页面上,而不是呈现其行为.
When this code runs, the refer_summary
variable actually contains a string which may contain HTML tags such as <b>
, <i>
etc., however, those tags are displayed on the page instead of rendering their behavior.
例如,在页面上它将显示< b>
而不是使内容变为粗体.
For example, on the page it would show <b>
rather actually making the content bold.
附加值后,如何呈现HTML标签?
How can I go about rendering the HTML tags when the value is appended?
在我的Django模板中,我使用 {%autoescape off%} {{content}} {%endautoescape%}
,所以当我第一次加载页面时,内容以粗体等正确显示.但是从javascript附加html时,我该怎么做?
In my Django template I use {% autoescape off %}{{content}}{% endautoescape %}
so when I first load the page, the content is rendered correctly with bold etc. But how can I do the same thing when appending the html from javascript?
感谢您的帮助!
推荐答案
您可以使用 document.write()
document.write('<html><body><h2>HTML</h2></body></html>');
但是要追加现有的HTML字符串,您需要获取要在其下插入HTML字符串的节点/标签的ID.
But to append existing HTML string, you need to get the id of the node/tag under which you want to insert your HTML string.
有两种方法可以实现此目的:
There are two ways by which you can possibly achieve this:
- 使用DOM-
var tag_id = document.getElementById('tagid');
var newNode = document.createElement('p');
newNode.appendChild(document.createTextNode('html string'));
- 使用innerHTML-
var tag_id = document.getElementById('tagid');
tag_id.innerHTML = 'HTML string';
这篇关于如何使用Javascript呈现HTML字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!