首页 > 解决方案 > 如何将 html 代码插入 prism 代码标签?

问题描述

我正在使用 Prism 在项目中显示我的组件,当我在<pre><code class="language-markup">...</code></pre>.

这是我的代码笔

<pre>
    <code class="language-markup">  

        &lt;!-- botão simples -->
        &lt;button class="btn left">Button&lt;/button>

        &lt;!-- botão com ícone na esquerda -->
        &lt;button class="btn left">&lt;i class="material-icons left">add&lt;/i>Button&lt;/button>

        &lt;!-- botão com ícone na direita -->
        &lt;button class="btn left">&lt;i class="material-icons right">add&lt;/i>Button&lt;/button>

    </code>
</pre>

输出 输出 1

但是,现在我想获取一些 innerHTML 并将其放入<code></code>标签中,但是当我这样做时它不起作用。

我的脚本

// Get all divs with the ".topic" class and returns a list of it
// @return list | array()
function getTopicList() {

    // Create the list
    let list = [];

    // Populate the list
    $('.topic').map(function() {
        list.push($(this));
    });

    // Returns the list
    return list;

}

// Set the example code inside a "code" tag
// @param topic       | jquery object
// @param exampleCode | string
function setExampleCode(topic, exampleCode) {

    // Replace "<" with "&lt;"
    exampleCode = exampleCode.replace(/</g, '&lt;');

    // Set the example's code inside the "code" tag
    $(topic).find('code').text(exampleCode);

}

// Get the HTML code inside the div as a string
// @param topic | jquery object
function generateExampleCode(topic) {

    // Get the HTML code as string
    let exampleCode = $(topic).find('.example').html();

    // Calls a function to append the code as a string into the div
    setExampleCode(topic, exampleCode);

}

// When the page is fully loaded
$(document).ready(function() {

    // Get a list of all the divs that have the ".topic" class
    let topicList = getTopicList();

    // Get the HTML code of all the ".topic" divs
    topicList.map(generateExampleCode);

});

输出 2

输出 2

即使我尝试将 a 附加<pre><code class="language-markup">...code...</code></pre>到 div 中,它也不起作用。我怎样才能做到这一点?有没有更简单的方法来做到这一点?

标签: javascripthtml

解决方案


我找到了一个解决方案:

当您通过 js/angular/vue/etc 插入代码时,您必须重新运行 Prism。

Prism.highlightAll()插入代码后使用该功能即可;


推荐阅读