javascript - 用 JS 转义尖括号

标签 javascript jquery dom escaping

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

当我编写包含片段的 HTML 文档时,我不想手动更改每个 <&lt; 。从我的 Angular 来看,最明显的方法是使用 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>

Current result:

enter image description here

Desired result:

enter image description here

最佳答案

这完全不是最好的方法,但我认为这比在<>上进行查找/替换要好。并且绝对胜过任何依赖 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> 的示例标签...

关于javascript - 用 JS 转义尖括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42333494/

相关文章:

php - 获取图像特定部分的坐标

jquery - 是否可以在不刷新页面的情况下更改元素上的光标?

javascript - 如何在删除重复项的同时合并对象数组

javascript - 嵌入式与链接的 JS/CSS

javascript - CSS 确定事件媒体查询

javascript - Google Apps 脚本通过邮件发送错误的表单输入

jquery - 将 html 附加到元素的更简洁的方法

javascript - 切换子元素的类(并删除同级元素)

javascript - 如何使用 Safari 移动设备检测输入文件中被忽略的大文件

javascript - 如何在 Firefox 中为 svg 的文本元素导入自定义字体?