鉴于下面的脚本,我想使用highlight.js和我的 javascript突出显示 html 语法,但它不起作用。
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/",
"`": "`",
"=": "=",
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, function(s) {
return entityMap[s];
});
}
$(document).ready(function() {
$("code").each(function(e) {
code = $(this).html();
raw = escapeHtml(code);
$(this).html(raw);
$(this)
.parent();
});
})
hljs.initHighlightingOnLoad();
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.0/highlight.min.js"></script>
<pre>
<code class="html">
<!DOCTYPE html>
<title>Title</title>
<style>body {width: 500px;}</style>
<script type="application/javascript">
function $init() {return true;}
</script>
<body>
<p checked class="title" id='title'>Title</p>
<!-- here goes the rest of the page -->
</body>
</code>
</pre>
在上面的脚本中,我尝试使用函数escapeHtml(string)
来转义任何给定的 html 语法实体,然后我调用了 highlight js 初始化,hljs.initHighlightingOnLoad();
但似乎它无法正常工作。
这有什么问题?
这不是最好的解决方案,我建议您找到一些方法来escape
在source code
您的页面上添加符号。在服务器端(php、nodejs、...其他)是可能的。
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.0/highlight.min.js"></script>
<pre>
<code class="html">
<!DOCTYPE html>
<title>Title</title>
<style>body {width: 500px;}</style>
<script type="application/javascript">
function $init() {return true;}
</script>
<body>
<p checked class="title" id='title'>Title</p>
<!-- here goes the rest of the page -->
</body>
</code>
</pre>
<script>
const entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/",
"`": "`",
"=": "=",
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, function(s) {
return entityMap[s];
});
}
document.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll('pre code').forEach((block) => {
block.innerHTML = escapeHtml(block.innerHTML);
hljs.highlightBlock(block);
});
});
</script>
这是一个很好的例子https://codepen.io/r3hab/pen/KKPWJJw
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句