【翻译】如何在AJAX生成的内容中再次运行Prism.js

前言

最近用一个十分轻量级的网页代码高亮Js库,应用到项目中发现了一个问题,对于静态的已经写好的代码,Prism的高亮插件是没有问题的,但是通过Ajax异步获取数据并修改DOM时发现,Prism高亮插件失效了,经过各种调试还是没办法解决,最后终于找到了解决办法。原文是英文版的,我做了简要的翻译,如有不妥之处还请指出。
以下是原文地址: http://schier.co/blog/2013/01/07/how-to-re-run-prismjs-on-ajax-content.html

原标题:How To Re-Run Prism.js On AJAX Content

译文

Prism.js is a great library to handle syntax highlighting for code blocks on a web page. However, since Prism runs automatically after being embedded (hence why you need to include it at the bottom of the HTML) content that is loaded later is not highlighted. After console logging the Prism object in Chrome developer tools I discovered a method called highlightAll() which can be used to force Prism to rerun on the current page.

Prism.js 是一个非常不错的用于处理网页中代码块的JavaScript库。然而,Prism.js嵌入网页后,你会发现通过AJAX后加载的内容并没有实现高亮。在我通过Chrome开发工具调试Prism时发现一个名为highlightAll()的方法,通过这个方法可以强制Prism再次在当前页面运行,并为通过AJAX后加载的内容添加高亮效果。

// Rerun Prism syntax highlighting on the current page
Prism.highlightAll();

If you don't want Prism rescanning the entire DOM you can selectively highlight elements with the highlightElement() function.

如果你不想让Prism再次查找新增的DOM节点内容,你可以使用highlightElement()函数来指定需要高亮的DOM节点内容。

// Say you have a code block like this
/**
  <pre>
    <code id="some-code" class="language-javascript">
      // This is some random code
      var foo = "bar"
    </code>
  </pre>
*/

// Be sure to select the inner <code> and not the <pre>
// Using plain Javascript
var block = document.getElementById('some-code')
Prism.highlightElement(block);

// Using JQuery
Prism.highlightElement($('#some-code')[0]);

It's as simple as that! I'm not sure why Prism doesn't include this tip on the website.

就是这么简单,但是我不知道为什么在Prism主页上没有关于这个贴士的说明。

Edit: The Prism guys tweeted me a link to the documentation on this: prismjs.com/extending.html#api

Prism的开发人员给了我一个如下地址的文档声明:prismjs.com/extending.html#api

官方地址:http://prismjs.com/

最后,附一张效果图:

 

 
posted @ 2015-09-15 12:46  悠扬的牧笛  阅读(553)  评论(0编辑  收藏  举报