javascript - 如何在特定元素中打印 html 代码标签?
问题描述
<div class="container">
<pre>
<code class="language-html">
<h1>I want to display html tag</h1>
</code>
</pre>
<pre>
<code class="language-html">
<h2>I also want to display html tag</h2>
</code>
</pre>
<pre>
<code class="language-not-html">
<b>I dont want to display html tag</b>
</code>
</pre>
<pre>
<code class="language-css">
html{
margin:20x;
}
</code>
</pre>
</div>
我需要有关如何在 div class="container" 中以纯文本显示我的 html 标签的帮助,但只能使用 javascript 或 jquery 对 class="language-html" 进行编码。我知道将标签更改为 < 和 > 但我不知道如何使用 javascript 来做到这一点。我也不想对其进行硬编码,因为我的网站的目的是拥有文本字段和一个按钮,每次我按下按钮时它都会创建一个新的<pre>
和<code>
标签。我想制作一个带有 highlight.js BTW 的网站。提前致谢
解决方案
这是预处理然后使用highlight.js的方法
如果您在跳过的代码上使用 nohighlight,hightlight 将不会给出控制台警告
// make hightlight.js happy:
const esc = str => str.replaceAll("<", "<");
document.querySelectorAll("code") // this will escape and trim all elements including nohighlight
.forEach(elem =>elem.innerHTML = esc(elem.innerHTML.trim()))
hljs.highlightAll()
// dynamic
document.getElementById("insert").addEventListener("click",function() {
const html = document.getElementById("htmlArea").value.trim();
if (html) {
const pre = document.createElement("pre");
const code = document.createElement("code");
code.className = "language-html language-xml hljs"
code.innerHTML = hljs.highlight(`${html}`,{language: 'xml'}).value
pre.appendChild(code)
document.querySelector(".container").appendChild(pre);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/highlight.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/styles/a11y-dark.min.css" />
<textarea id="htmlArea"><h1>Some HTML</h1></textarea> <button type="button" id="insert">Insert</button>
<div class="container">
<pre>
<code class="language-html">
<h1>I want to display html tag</h1>
</code>
</pre>
<pre>
<code class="language-html">
<h2>I also want to display html tag</h2>
</code>
</pre>
<pre>
<code class="languagenot-html nohighlight">
<b>I dont want to display html tag</b>
</code>
</pre>
<pre>
<code class="language-css">
html{
margin:20x;
}
</code>
</pre>
</div>
推荐阅读
- html - 对齐内容:空格之间不起作用
- vim - How to hide empty lines?
- javascript - 如果使用momentjs在两次之间,如何检查当前时间?
- javascript - Angular 6 - html中的绑定值和索引
- sql - 在查询顶部定义日期
- java - 如何为以下 json 创建 POJO?
- python - 如何使用列表对多索引数据透视表的列标题进行排序
- apache-spark - 我可以让 Spark 仅在必要的行上运行 UDF 吗?
- python - 为什么我们需要在 get dummy 函数中使用 drop_first 参数
- kubernetes - 有没有办法在 Log4Net.config 中使用 Kubernetes Container 环境变量?