【问题标题】:Dynamic Code Snippet Display In JavascriptJavascript 中的动态代码片段显示
【发布时间】:2018-08-15 15:04:34
【问题描述】:

我正在写一个JS函数:

showCodeSnippet(fileName)
Input: Local File Name 
Output: Display Code in HTML

我知道限制在浏览器中访问本地文件的安全约束,但设法创建了一个变通解决方案。

请考虑此代码(适用于 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 包含一些示例 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;
}

输出 HTML 页面:

问题陈述:

语法高亮不工作。

试过了:

  • Google 代码美化
  • 棱镜荧光笔

这些荧光笔在 HTML 标签下的静态代码的情况下工作正常。

有人可以提供任何提示 - 这个问题的根本原因,还是我应该考虑其他方向来实现这种类型的功能?

谢谢

【问题讨论】:

    标签: javascript code-snippets google-code-prettify


    【解决方案1】:

    我发现 Chrome 有所不同。当我使用 Firefox 时,我遇到了和你一样的问题。稍等,我会检查一些东西:)

    当您在附加后添加PR.prettyPrint(); 时,漂亮打印也将在 FireFox 中工作。似乎代码在 FireFox 中不支持自动重绘:(

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 2023-02-10
      • 2021-03-22
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 2015-08-22
      相关资源
      最近更新 更多