Cannot read property of NULL

泄露秘密 提交于 2019-12-25 11:52:35

问题


I have the following html file in which I try to highlight some code using a web worker:

<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>

But I get an error saying: Uncaught TypeError: Cannot read property 'textContent' of null (worker.postMessage(content.textContent));

Is there a solution?


回答1:


Add id="code" attribute on code element: 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>


来源:https://stackoverflow.com/questions/43203656/cannot-read-property-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!