我正在使用Prism在项目中显示组件,当我在<pre><code class="language-markup">...</code></pre>
内编写代码本身时,它运行良好。
这是我的codepen。
<pre>
<code class="language-markup">
<!-- botão simples -->
<button class="btn left">Button</button>
<!-- botão com ícone na esquerda -->
<button class="btn left"><i class="material-icons left">add</i>Button</button>
<!-- botão com ícone na direita -->
<button class="btn left"><i class="material-icons right">add</i>Button</button>
</code>
</pre>
但是,现在我想抓取一些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 "<"
exampleCode = exampleCode.replace(/</g, '<');
// 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
即使我尝试将<pre><code class="language-markup">...code...</code></pre>
附加到div中,它也不起作用。我怎样才能做到这一点?有没有更简单的方法可以做到这一点?
答案 0 :(得分:0)
我找到了解决方法:
当您通过js / angular / vue / etc插入代码时,必须重新运行Prism。
插入代码后,只需使用Prism.highlightAll()
函数即可