web开发报错合集(基于openlayers)

发布时间 2023-03-27 23:45:10作者: 雨崩

1、Uncaught TypeError: Cannot read properties of undefined (reading 'getViewport')

 

 代码:(位于代码页最上面)

 1         // 添加一个按钮,用于触发样式函数
 2         var button = document.createElement('button');
 3         button.innerHTML = 'inSec';
 4         button.style.position = 'absolute';//
 5         button.style.top = '1px';
 6         button.style.right = '40px';
 7         map.getViewport().appendChild(button);
 8 
 9         // 当按钮被点击时,重新设置样式函数
10         button.onclick = function() {
11     
12         };

reason:

当前getViewport标签没有定义,html的执行顺序是从上到下,在标签还没有加载的时候该方法就被调用了,所以会出没有定义的错误。

 因此需要调整当前js代码顺序

参考:https://blog.csdn.net/mini_1251861209/article/details/81867575

2、将上述代码改为代码位置最下面

 

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

reason:Cannot read properties of 都是渲染错误 不能获取属性。因为 JavaScript 中操作DOM元素的函数方法需要在 HTML 文档渲染完成后才可以使用,如果没有渲染完成,此时的 DOM 树是不完整的,这样在调用一些 JavaScript 代码时就可能报出 "undefined" 错误。

1、addEventListener 放在绑定的元素添加渲染完成后再使用;

2、使用 window.onload 或 $(document).ready()

1 window.οnlοad=function(){
2     // code
3 };
4 $(document).ready(function () {
5     // code
6 });

参考:https://blog.csdn.net/Tsailing666/article/details/128076116

 

3、学习如何创建button及绑定对应的功能