问题以更紧凑和清晰的形式完全重写。
当我编写包含片段的 HTML 文档时,我不想手动更改每个 <
至<
。从我的 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, '<')
.replace(/>/g, '>');
};
</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:
Desired result:
最佳答案
这完全不是最好的方法,但我认为这比在<>
上进行查找/替换要好。并且绝对胜过任何依赖 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/