我<pre>在我的博客中使用标签来发布代码.我知道我必须要改变<到<和>到>.我需要转义任何其他字符才能获得正确的HTML吗?
Sal*_*n A 11
如果您使用<pre>标记在博客上显示HTML标记会发生什么:
<pre>Use a <span style="background: yellow;">span tag with style attribute</span> to hightlight words</pre>Run Code Online (Sandbox Code Playgroud)
这将通过HTML验证,但它是否产生预期的结果?不.正确的方法是:
<pre>Use a <span style="background: yellow;">span tag with style attribute</span> to hightlight words</pre>Run Code Online (Sandbox Code Playgroud)
另一个例子:如果使用pre标签显示其他语言代码,仍然需要HTML编码:
<pre>if (i && j) return;</pre>
Run Code Online (Sandbox Code Playgroud)
这可能会产生预期的结果,但它是否通过HTML验证?不.正确的方法是:
<pre>if (i && j) return;</pre>
Run Code Online (Sandbox Code Playgroud)
简而言之,对预标签的内容进行HTML编码就像使用其他标签一样.
<xmp>标签这不是众所周知的,但它确实存在,甚至chrome仍然支持它,但是不推荐使用配对 <xmp>标签- 它只是为了你,但它是一个非常简单的方法如何做你的个人,例如DOCS.甚至w3.org WIKI在例子中说"不,真的.不要使用它."
你可以把任何html(不包括</xmp>结束标记)放在里面<xmp></xmp>
<xmp>
<html> <br> just any other html tags...
</xmp>
Run Code Online (Sandbox Code Playgroud)
正确的版本可以被视为存储为STRING的HTML,并在某些转义函数的帮助下显示.
只记得一件事 - 类C语言中的字符串通常用单引号或双引号编写 - 如果你将字符串换成double =>你应该转义双精度(可以说是\),如果你将你的字符串换成单个=>转义单打(可能与\...)
服务器端脚本语言通常具有一些内置函数来转义HTML.
<?php
$html = "<html> <br> or just any other HTML"; //store html
echo htmlspecialchars($html); //display escaped html
?>
Run Code Online (Sandbox Code Playgroud)
在客户端脚本中可以实现与服务器端类似的方法,JavaScript,据我所知,没有内置函数(这是非常合乎逻辑的),但是如果你使用一些框架/库,比如jQuery,那么可以这种方式使用的函数.
只要记住与服务器端相同的东西 - 在类C语言中,转义你已经包裹了你的字符串的引号......
var html = '<html> <br> or just any other HTML';
var $elementToInsertEscapedHTMLto = jQuery("XXX"); //XXX is selector, e.g. CSS selector
$elementToInsertEscapedHTMLto.text( html );
Run Code Online (Sandbox Code Playgroud)