【翻譯】如何在AJAX產生的內容中再次運行Prism.js

來源:互聯網
上載者:User

標籤:

一、前言

      最近用一個十分輕量級的網頁代碼高亮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 pagePrism.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 Javascriptvar block = document.getElementById(‘some-code‘)Prism.highlightElement(block);// Using JQueryPrism.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

 聲明:本部落格原創文字只代表本人工作中在某一時間內總結的觀點或結論,與本人所在單位沒有直接利益關係。非商業,未授權貼子請以現狀保留,轉載時必須保留此段聲明,且在文章頁面明顯位置給出原文串連。

 

【翻譯】如何在AJAX產生的內容中再次運行Prism.js

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.