[英]Dynamic Code Snippet Display In Javascript
I am writing a JS function:我正在编写一个 JS 函数:
showCodeSnippet(fileName)
Input: Local File Name
Output: Display Code in HTML
I know about the security constraints which restrict accessing local files in browser, but managed to create a workaround solution.我知道限制在浏览器中访问本地文件的安全约束,但设法创建了一个变通解决方案。
Please consider this Code (working on Firefox 57.0, 64-bit):请考虑此代码(适用于 Firefox 57.0,64 位):
<html>
<head>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
</head>
<body>
<script>
async function showCodeSnippet(fileName)
{
const response = await fetch(fileName);
const text = await response.text();
var parser = new DOMParser();
var domString = "<pre class=\"prettyprint\">" + text + "</pre>";
var html = parser.parseFromString(domString, 'text/html');
document.body.append(html.body.firstChild);
}
</script>
<script>
showCodeSnippet('Code.txt');
</script>
</body>
</html>
Code.txt contains some sample C++ code: Code.txt 包含一些示例 C++ 代码:
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
Problem Statement:问题陈述:
Syntax Highlighting is NOT working.语法高亮不起作用。
Tried:尝试:
These highlighters work fine in case of static code under tags in HTML.这些荧光笔在 HTML 标签下的静态代码的情况下工作正常。
Can someone please provide any hint - root cause of this problem or shall I think in any other direction to achieve this type of functionality ?有人可以提供任何提示 - 此问题的根本原因,还是我应该考虑其他任何方向来实现此类功能?
Thanks谢谢
I see a difference in Chrome.我发现 Chrome 有所不同。 When i Use Firefox, i get the same problem as you.
当我使用 Firefox 时,我遇到了和你一样的问题。 Hold on, i will check some things :)
稍等,我会检查一些东西:)
When you add PR.prettyPrint();
当你添加
PR.prettyPrint();
after your appending, the pretty-print will also work in FireFox.附加后,漂亮的打印也将在 FireFox 中工作。 seems that the automated repaint is not supported in FireFox by the code :(
似乎代码在 FireFox 中不支持自动重绘:(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.