欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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