javascript - 如何将 html 代码插入 prism 代码标签?
问题描述
我正在使用 Prism 在项目中显示我的组件,当我在<pre><code class="language-markup">...</code></pre>
.
这是我的代码笔。
<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
即使我尝试将 a 附加<pre><code class="language-markup">...code...</code></pre>
到 div 中,它也不起作用。我怎样才能做到这一点?有没有更简单的方法来做到这一点?
解决方案
我找到了一个解决方案:
当您通过 js/angular/vue/etc 插入代码时,您必须重新运行 Prism。
Prism.highlightAll()
插入代码后使用该功能即可;
推荐阅读
- python - 强化算法似乎在学习,但脚本卡住了,代理没有重置
- ruby-on-rails - 为什么 webpacker:compile 在 javascript_pack_tag 中插入特定的主机名?
- domain-driven-design - 按 id 检索实体引用其他聚合
- c# - 循环遍历类属性并获得不同的值
- python - 将 csv 列的某些值替换为另一个列中的值
- ruby-on-rails - 满足条件后如何自动更新父级?
- bash - 根据索引从数组中删除多个元素
- electron - 如何在我的 Electron 应用程序的客户端代码中导入 Node 模块?
- html - ReactJs - SPA 导航栏
- c - 套接字:连接失败,连接被拒绝