zoukankan      html  css  js  c++  java
  • 【翻译】如何在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/

    最后,附一张效果图:

     作者:悠扬的牧笛

     博客地址:http://www.cnblogs.com/xhb-bky-blog/p/4809295.html

     声明:本博客原创文字只代表本人工作中在某一时间内总结的观点或结论,与本人所在单位没有直接利益关系。非商业,未授权贴子请以现状保留,转载时必须保留此段声明,且在文章页面明显位置给出原文连接。

     
  • 相关阅读:
    [Python] Marshmallow QuickStart
    [Python]Marshmallow 代码
    [python]Flask-migrate简单入门
    [数据库]Sqlite使用入门
    [Python] dict对象的keys()和values()返回的值,是否总是保证一一对应?
    【Weiss】【第03章】练习3.20:中缀表达式转后缀表达式
    【Weiss】【第03章】练习3.19:计算后缀表达式
    【Weiss】【第03章】练习3.18:检查平衡符号
    【Weiss】【第03章】练习3.17:懒惰删除
    【TIJ4】第六章全部习题【习题未完成】
  • 原文地址:https://www.cnblogs.com/xhb-bky-blog/p/4809295.html
Copyright © 2011-2022 走看看