我有以下html文件,我尝试使用网络工作者突出显示一些代码:
<link rel="stylesheet" href="./highlight/styles/default.css">
<script src="./highlight/highlight.pack.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
if (typeof(Worker) !== "undefined") {
addEventListener('load', function() {
var code = document.querySelector('#code');
var worker = new Worker('worker.js');
worker.onmessage = function(event) { code.innerHTML = event.data; }
worker.postMessage(code.textContent);
})
} else {
}
</script>
<pre><code>
// This is a generated file with many packages
`ifdef MACRO_1
`else
package pkg_1;
typedef logic [1:0] t;
typedef enum t {
IDLE = 2'd0
, ARMED = 2'd1
, WRITE = 2'd2
, BUSY = 2'd3
} e;
</code></pre>
&#13;
但我得到一个错误说:未捕获的TypeError:无法读取属性&#39; textContent&#39; of null(worker.postMessage(content.textContent));
有解决方案吗?
答案 0 :(得分:2)
在代码元素上添加id =“code”属性:https://jsbin.com/daqijafoca/edit?html,output
<link rel="stylesheet" href="./highlight/styles/default.css">
<script src="./highlight/highlight.pack.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
if (typeof(Worker) !== "undefined") {
addEventListener('load', function() {
var code = document.querySelector('#code');
var worker = new Worker('worker.js');
worker.onmessage = function(event) { code.innerHTML = event.data; }
worker.postMessage(code.textContent);
})
} else {
}
</script>
<pre><code id="code">
// This is a generated file with many packages
`ifdef MACRO_1
`else
package pkg_1;
typedef logic [1:0] t;
typedef enum t {
IDLE = 2'd0
, ARMED = 2'd1
, WRITE = 2'd2
, BUSY = 2'd3
} e;
</code></pre>