问题
I simply want to create something like that:
<strong>blah blah</strong>
I've been trying to do this for a long time though for some reason whenever I put the code and the pre tags they don't do what they should. They do unformat the content - I don't see any formatting, though the tags don't appear. For example, I wrote :
<pre><b>abc</b></pre>
The abc is appearing not bold, but I can't see the tag itself. How can I do that? I don't want to use entities like &fdaf; because I am not writing the incoming text
回答1:
Like mkluwe also said, you should use JavaScript (or a server-side script) to properly escape any user input. Here's another JavaScript function you could try:
String.prototype.escapeHTML = function () {
return(
this.replace(/>/g,'>').
replace(/</g,'<').
replace(/"/g,'"')
);
};
var codeEl = document.getElementById('test');
if (codeEl) {
codeEl.innerHTML = codeEl.innerHTML.escapeHTML();
}
I haven't tested this in IE, but it should work there in theory. Here's a page where you can view the results: http://jsbin.com/oruri5/2/edit
回答2:
Use the <xmp>
tag.
E.g.
<xmp>
<html>
<body>This is my html inside html.</body>
</html>
</xmp>
You can also add styles and formatting inside <xmp>
as well.
回答3:
How about replacing the incoming texts by <
and >
The tags should be visible in source view, but not "in normal view".
回答4:
You could use some javascript to change elements on the fly.
If you use jQuery:
$( 'pre' ).text( $( 'pre' ).html() );
does the trick.
回答5:
The easiest way I know is to replace the < and > with < and > that way it's not html anymore. There are several other codes like these for & symbols, etc.
Where is the text coming from? If it's in javascript than you're easiest way would be to do a regex replace in javascript.
回答6:
You have to write stuff like &fdaf; because the browser refuses to believe that you mean <pre> for everything. This is the correct behavior, else how would you ever escape from a <pre> section? You have to go through the doc and for every less-than sign substitute <. You do not have to do that for the greater-than sign or for ampersand (usually).
回答7:
Don't use <xmp>, <plaintext> and <listing> Use as suggested by MDN:
Use the <pre> element or, if semantically adequate, the <code> element
instead. Note that you will need to escape the '<' character as '<'
to make sure it is not interpreted as markup."
As you can see in this link: MDN xmp
回答8:
to build on @mkluwe's answer, here is an example:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
</head>
<body>
<pre>
<a href="http://localhost:3000/l/1/2/3" target="_blank">
<img src="http://localhost:3000/b/1/2/3/4" target="_blank">
</a>
</pre>
<script>
$( 'pre' ).text( $( 'pre' ).html() );
</script>
</body>
</html>
来源:https://stackoverflow.com/questions/5406373/how-can-i-display-html-tags-inside-an-html-document