报错Cannot read property ‘addEventListener‘ of null
程序员文章站
2022-03-04 11:03:26
...
<head>
<script type="text/javascript">
var myul = document.getElementById('test-ul');
var list = document.querySelectorAll('ul li');
myul.addEventListener('click', function(ev){
var ev = ev || window.event;
var target = ev.target || ev.srcElemnt;
for(var i = 0, len = list.length; i < len; i++){
if(list[i] == target){
alert(i + "----" + target.innerHTML);
}
}
});
</script>
</head>
<body>
<ul id="test-ul">
<li>index = 0</li>
<li>index = 1</li>
<li>index = 2</li>
<li>index = 3</li>
</ul>
</body>
原因:脚本在head中,在body还没加载完之前,脚本先加载了,所以找不到监听对象。
解决方法:
一、将脚本放到后面加载
<head>
</head>
<body>
<ul id="test-ul">
<li>index = 0</li>
<li>index = 1</li>
<li>index = 2</li>
<li>index = 3</li>
</ul>
<script type="text/javascript">
var myul = document.getElementById('test-ul');
var list = document.querySelectorAll('ul li');
myul.addEventListener('click', function(ev){
var ev = ev || window.event;
var target = ev.target || ev.srcElemnt;
for(var i = 0, len = list.length; i < len; i++){
if(list[i] == target){
alert(i + "----" + target.innerHTML);
}
}
});
</script>
</body>
二、使用window.οnlοad=function(){},在页面加载完,该方法才被触发
<head>
<script type="text/javascript">
window.onload=function(){
var myul = document.getElementById('test-ul');
var list = document.querySelectorAll('ul li');
myul.addEventListener('click', function(ev){
var ev = ev || window.event;
var target = ev.target || ev.srcElemnt;
for(var i = 0, len = list.length; i < len; i++){
if(list[i] == target){
alert(i + "----" + target.innerHTML);
}
}
});
}
</script>
</head>
<body>
<ul id="test-ul">
<li>index = 0</li>
<li>index = 1</li>
<li>index = 2</li>
<li>index = 3</li>
</ul>
</body>
上一篇: php头编码实例设置方法及代码
下一篇: JAVA8中Optional 使用详解
推荐阅读
-
解决微软云Azure Function运行报错-Value cannot be null. (Parameter ‘provider‘)
-
js报错 Cannot read property 'getAttribute' of null
-
Vue报错:Uncaught TypeError: Cannot assign to read only property’exports‘ of object
-
npm ERR! Cannot read property 'path' of null
-
js报错 Cannot read property 'getAttribute' of null
-
微信小程序报Cannot read property 'setData' of undefined的错误
-
webpack报错Cannot read property 'presetToOptions' of undefined
-
Extjs4---Uncaught TypeError: Cannot read property ‘items’ of undefined
-
JavaScript Uncaught TypeError: Cannot read property 'value' of null
-
Cannot read property 'tap' of undefined