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>
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页:
问题陈述:
尝试:
有人可以提供任何提示-这个问题的根本原因,还是我应该在任何其他方向来实现这种类型的功能?