【发布时间】:2021-07-30 01:35:04
【问题描述】:
我实际上是在尝试为基于 AJAX 和弹出窗口的网站制作源代码查看器。这将允许我自定义查看器。我正在使用 hightlight.js 进行语法,但这是我第一次使用该库。
过程很简单:
- 我正在使用 AJAX 获取页面 HTML 及其 URL(这里我使用 jQuery)
- 我将结果内容放在一个窗口中并显示出来。
- 在窗口中,Highlight.js (应该)对代码进行着色
与本主题类似:Programmatically open "View Source" HTML Window in Browser with Javascript?,但还具有语法高亮显示。不幸的是,窗口显示了里面的代码,但是那个没有着色。
这是整个函数(它为跨域请求提供后备)
function show_source(link) {
$.ajax({
method: "GET",
url: link,
dataType: "html",
success: function (data) {
var source = data;
//parse special chars
source = source.replace(/</g, "<").replace(/>/g, ">");
// add <pre> tags to preserve whitespace
source = "<!DOCTYPE html><html><head><link rel='stylesheet' href='/css/include/default.css'><script src='/lib/include/highlight.pack.js'></script><script>hljs.initHighlightingOnLoad(document.getElementById('code'));</script></head><body><pre id='code' class='html'>" + source + "</pre></body></html>";
//now open the window and set the source as the content
var sourceWindow = window.open('', 'Source code of ' + link + '', 'height=800,width=800,scrollbars=1,resizable=1');
if (!sourceWindow || sourceWindow.closed || typeof sourceWindow.closed == 'undefined') {
alert("Please allows this popup window to be shown");
} else {
sourceWindow.document.write(source);
sourceWindow.document.close(); //close the document for writing, not the window
//give source window focus
if (window.focus) {
sourceWindow.focus();
}
}
},
error: function(){
window.open("view-source:"+link+"", "_blank");
}
});
}
但我多次验证了我的代码,一切似乎都很好。 Firefox 开发工具显示 CSS 和 JS 文件已成功加载(GET)并且没有 JS 错误。 问题出在哪里?谢谢你帮助我。
编辑:添加了一个缺失的括号,但效果不大。
【问题讨论】:
-
你能做一个jsfiddle吗?
-
只要我知道,
highlight.js需要知道必须突出显示的内容。那么你具体想做什么呢。 -
因此,正如我在 highlight.js 文档中所读到的那样,您应该使用一个类命名要突出显示的元素,在我的情况下,我想使用 HTML 语法,并且当我们初始化对象时,它应该自动完成......但不是。
-
无法制作jsfiddle,它说我只输入js内容而不是html...奇怪
标签: javascript jquery html ajax highlight.js