简体   繁体   English

在代码段HTML中呈现xml和html标签

[英]rendering xml and html tags in a code snippet HTML

simply,how to render code snippet with <html> tags like this 简单地,如何使用<html>标签呈现代码片段

<div id="container">
   <div id="header_area"><tiles:insertAttribute name="header"  /></div>
   <div id="body_area"><tiles:insertAttribute name="body" /></div>
   <div id="sidebar_area"><tiles:insertAttribute name="sidebar" /></div>
   <div id="footer_area"><tiles:insertAttribute name="footer" /></div>
</div>

i found this code.but it adds endtag to all /> 我找到了此代码。但是它向所有/>添加了结尾标签

function encodePreElements() {
    var pre = document.getElementsByTagName('pre');
    for(var i = 0; i < pre.length; i++) {
        var encoded = htmlEncode(pre[i].innerHTML);
        pre[i].innerHTML = encoded;
    }
};

function htmlEncode(value) {
   var div = document.createElement('div');
   var text = document.createTextNode(value);
   div.appendChild(text);
   return div.innerHTML;
}

so above code will be like this 所以上面的代码会像这样

<div id="container">
    <div id="header_area"><tiles:insertattribute name="header"></tiles:insertattribute></div>
    <div id="body_area"><tiles:insertattribute name="body"></tiles:insertattribute></div>
    <div id="sidebar_area"><tiles:insertattribute name="sidebar"></tiles:insertattribute></div>
    <div id="footer_area"><tiles:insertattribute name="footer"></tiles:insertattribute></div>
</div>

.innerHTML renders correctly in javascript alert . .innerHTML可在javascript alert正确呈现。 so how can i render code snippet like first? 所以我怎样才能像第一个那样呈现代码片段? what is the easy way to do this process? 进行此过程的简单方法是什么?

OK, so I assume that in your question, the first quoted block is embedded inside a <pre> element, like this: <pre> <div id="container"> ... </div> </pre> 好的,所以我假设在您的问题中,第一个引用的块嵌入在<pre>元素内,如下所示: <pre> <div id="container"> ... </div> </pre>

And you are trying to convert that so that it becomes: <pre> &lt;div ... </pre> 并且您正在尝试将其转换为<pre> &lt;div ... </pre>

The problem is that when the page is loaded, the contents of <pre> is loaded into the DOM . 问题在于,在加载页面时, <pre>的内容将加载到DOM中 When you get the value of pre[i].innerHTML , it returns you a value that accurately represents the DOM state, but is not the same as your original HTML. 当您获得pre[i].innerHTML的值时,它将返回一个可以准确表示DOM状态但与原始HTML不同的值。

If you want to preserve the exact HTML used in the page, you need to encode that HTML when you generate the page . 如果要保留页面中使用的确切HTML,则在生成page时需要对HTML进行编码 By the time any JavaScript has access to the content, it's too late - the original HTML is gone, and all you have left is the DOM contents. 当任何JavaScript都可以访问内容时,已经为时已晚-原始HTML消失了,剩下的就是DOM内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM