【翻译】如何在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后加载的内容添加高亮效果。
1 2 | // 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节点内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 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/
最后,附一张效果图:
—— EOF ——
作者:悠扬的牧笛
地址:https://www.cnblogs.com/xhb-bky-blog/p/4809295.html
声明:本博客原创文字只代表本人工作中在某一时间内总结的观点或结论,与本人所在单位没有直接利益关系。非商业,未授权贴子请以现状保留,转载时必须保留此段声明,且在文章页面明显位置给出原文连接。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能