如何在网页上显示HTML片段,而不需要将每个<替换为<>和>?
换句话说,是否有一个标记表示在点击结束标记之前不呈现HTML ?
如何在网页上显示HTML片段,而不需要将每个<替换为<>和>?
换句话说,是否有一个标记表示在点击结束标记之前不呈现HTML ?
当前回答
//To show xml tags in table columns you will have to encode the tags first
function htmlEncode(value) {
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
html = htmlEncode(html)
其他回答
我使用<xmp>,就像这样: http://jsfiddle.net/barnameha/hF985/1/
这是目前为止在大多数情况下最好的方法:
<pre><code>
code here, escape it yourself.
</code></pre>
我会投票给第一个提出这个建议的人,但我没有名气。为了那些试图在网上找到答案的人,我不得不说些什么。
JavaScript字符串文字可以用于跨多行编写HTML。显然,这个解决方案需要JavaScript,特别是ECMA6。
.createTextNode with CSS white-space: pre-wrap;很管用。
. innertext单独也可以。运行下面的代码片段。
let codeBlock = ` <!DOCTYPE HTML> <html lang="en"> <head> <title>My Page</title> </head> <body> <h1>Welcome to my page</h1> <p>I like cars and lorries and have a big Jeep!</p> <h2>Where I live</h2> <p>I live in a small hut on a mountain!</p> </body> </html> ` const codeElement = document.querySelector("#a"); let textNode = document.createTextNode(codeBlock); codeElement.appendChild(textNode); const divElement = document.querySelector("#b"); divElement.innerText = codeBlock; #a { white-space: pre-wrap; } <div id=a> </div> <div id=b> </div>
如果您正在寻找与框架一起工作的解决方案。
const code = `
<div>
this will work in react
<div>
`
<pre>
<code>{code}</code>
</pre>
你可以用css给它一个漂亮的外观:
pre code {
background-color: #eee;
border: 1px solid #999;
display: block;
padding: 20px;
}
你可以使用像PHP这样的服务器端语言来插入原始文本:
<?php
$str = <<<EOD
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Minimal HTML5">
<meta name="keywords" content="HTML5,Minimal">
<title>This is the title</title>
<link rel='stylesheet.css' href='style.css'>
</head>
<body>
</body>
</html>
EOD;
?>
然后转储$str htmlencoded的值:
<div style="white-space: pre">
<?php echo htmlentities($str); ?>
</div>