使用JS

时间:2017-02-19 22:08:28

标签: javascript jquery dom escaping

问题以更紧凑和清晰的形式完全重写。

当我编写带有片段的HTML文档时,我不想手动将每个<更改为&lt;。从我的角度来看,最明显的方法是使用JS来完成这项任务,如下所示。但是,它不起作用。

如何解决?

Fiddle

<head>
    <style>
        body {
            width: 500px;
        }
    </style>
    <script>
        window.onload = function() {
            var pre = document.querySelector("#html-example");
            pre.innerHTML = pre.innerHTML
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
        };
    </script>
</head>
<body>
    <h1>
        Chapter 1
    </h1>
    <p>
        Here is the first tutorial of HTML for total beginners.
        Typical HTML contains of 2 main parts: head and body.
        Here is an exmaple of how it looks:
    </p>
    <pre id="html-example" style="background-color: aliceblue;">
<head>
    Head content goes here. Only very technical things
</head>
<body>
    Body content goes here. Not necessary very technical.
    For example, something about cats.
</body>
    </pre>
    <p>
        ..............
    </p>
</body>
  

目前的结果:

enter image description here

  

期望的结果:

enter image description here

1 个答案:

答案 0 :(得分:1)

这完全不是最好的方法,但我认为它比在<>上执行查找/替换更好,并且绝对胜过依赖于javascript中的HTML解析的任何解决方案(从不这样做... )。

在您编写的HTML文档中,您可以使用<script type="text/html">标记而不是现在使用的<pre>标记来包含代码示例。

默认情况下,浏览器不会对此类标记执行任何操作。但是在javascript中,您可以像使用document.querySelector或任何其他DOM api方法的任何其他元素一样选择它。

这意味着在文档加载时,您可以使用文本节点将所有<script>标记替换为<pre>标记:

Array.from(document.querySelectorAll(".js-example"))
  .forEach(el => {
    const textNode = document.createTextNode(el.innerHTML)
    const pre = document.createElement("pre");

    pre.style.backgroundColor = "aliceblue";
    pre.appendChild(textNode);

    el.parentElement.insertBefore(pre, el);
    el.parentElement.removeChild(el);

  })
<h1>
  Chapter 1
</h1>
<p>
  Here is the first tutorial of HTML for total beginners. Typical HTML contains of 2 main parts: head and body. Here is an exmaple of how it looks:
</p>

<script class="js-example" type="text/html">
<head>
  Head content goes here. Only very technical things
</head>

<body>
  Body content goes here. Not necessary very technical. For example, something about cats.
</body>
</script>

<p>
  ..............
</p>

<p>
  Another example:
  <script class="js-example" type="text/html">
An unclosed tag: </p>
  </script>
...
</p>

免责声明:我仅将此用于简单示例...如果这是您网站的主要目标,我会投入更优雅的解决方案中提到的解决方案。另外,我认为此解决方案不支持包含自己的</script>标记的示例...

相关问题