如何将HTML代码插入棱镜代码标签?

时间:2019-06-24 17:42:24

标签: javascript html

我正在使用Prism在项目中显示组件,当我在<pre><code class="language-markup">...</code></pre>内编写代码本身时,它运行良好。

这是我的codepen

<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>

输出 output 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

output 2

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

1 个答案:

答案 0 :(得分:0)

我找到了解决方法:

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

插入代码后,只需使用Prism.highlightAll()函数即可