javascript - 从脚本更新时如何在 <pre> 中使用 html 标签

标签 javascript html pre

我有一条短信<pre id="printed-table">bunch of monkeys</pre> 。我想用 javascript window.onload 处理文本突出显示单词 monkeys .

所以,它应该看起来像

bunch of monkeys
when page is loaded.

I have a script

<script type="text/javascript">
  window.onload = function() {
    var p = document.getElementById("printed-table");
    var t = p.firstChild.nodeValue;
    p.firstChild.nodeValue = t.replace(/monkeys/gmi, function(a) {
return "<strong>" + a + "</strong>"; } ) } 
</script>

但是当页面加载时,它看起来像

bunch of &lt;strong&gt;monkeys&lt;/strong&gt;

我错过了什么?

谢谢。

最佳答案

尝试设置p.innerHTML而不是p.firstChild.nodeValue 。如果这样做,您将设置元素的实际 HTML 内容,而不是 <pre> 内文本节点的(文本)值。元素。

  window.onload = function() {
    var p = document.getElementById("printed-table");
    var t = p.firstChild.nodeValue;
    p.innerHTML = t.replace(/monkeys/gmi, function(a) {
      return "<strong>" + a + "</strong>"; } ) } 
 <pre id="printed-table">bunch of monkeys</pre>

关于javascript - 从脚本更新时如何在 <pre> 中使用 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29857767/

相关文章:

css - contenteditible 在悬停时不显示边框

jquery - Div 类仅隐藏在 jQuery Tab 中

javascript - HTML5 音频 API - "audio resources unavailable for AudioContext construction"

javascript - 回调不更新状态

javascript - 在新选项卡中打开时网址显示不同的 php 文件

javascript - 为什么这个脚本只给出一半的输出?

php - HTML 显示文章

html - 如何将长空格推到预包装 html 中的下一行

html - 避免使用像 <pre> 这样的 HTML 标签的 XSS

javascript - 执行具有复杂参数的函数