首页 > 解决方案 > 如何在特定元素中打印 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 的网站。提前致谢

标签: javascripthtmljqueryreplacehighlight.js

解决方案


这是预处理然后使用highlight.js的方法

如果您在跳过的代码上使用 nohighlight,hightlight 将不会给出控制台警告

// make hightlight.js happy:
const esc = str => str.replaceAll("<", "&lt;");
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>


推荐阅读