javascript 无法获取属性“addEventListener”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24265385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:28:43  来源:igfitidea点击:

Unable to get property 'addEventListener'

javascripthtmlasp.net

提问by Ben Clarke

I have been working on a small aspect of my application today and wanted to get a sliding bar on my application. I asked a question this morning where there was some good answers. I have recently wanted to try and answer that i ws given using Script, CSSand HTML.

我今天一直在研究我的应用程序的一个小方面,并希望在我的应用程序上获得一个滑动条。今天早上我问了一个问题,那里有一些很好的答案。我最近想尝试回答我使用ScriptCSSHTML给出的答案。

I am getting to problem to get the Scriptworking as it keeps coming up with an error saying:

我遇到了让脚本工作的问题,因为它不断出现错误提示:

 0x800a138f - JavaScript runtime error: Unable to get property 'addEventListener' of undefined or null reference

This is the Script:

这是脚本

<script type="text/javascript">

    var desktops = document.querySelectorAll('.desktop');

    function hide(element) {
        element.style.setProperty('left', '-100%', element.style.getPropertyPriority('left'));
    }

    function hideAll() {
        for (var i = 0; i < desktops.length; i++) {
            hide(desktops[i]);
        }
    }

    function show(element) {
        element.style.setProperty('left', '0', element.style.getPropertyPriority('left'));
    }

    document.getElementById('link-one').addEventListener('click', function () {
        hideAll();
        show(document.getElementById('one'));
    }, false);


    show(document.getElementById('one'));
</script>

Here is the HTML:

这是HTML

<ul>
<li id="link-one">
  <div>1</div>
  <div>One</div>
</li>
</ul>

<div id="one" class="desktop">
  <h1>Sidebar Example</h1>
  <p>This is 1</p>
  <p>Something here.</p>
</div>

From what I can work out its not being able to find the ID?

据我所知,它无法找到 ID?

回答by freefaller

The problem is that you're running the script BEFORE the elements on the page have been created. That is why the getElementByIdis returning null.

问题是您在创建页面上的元素之前运行脚本。这就是为什么getElementById正在返回null

There are several ways to get around this...

有几种方法可以解决这个问题......

  • (as commented by Kendall) you can move the script to the end of the <body>
  • You can put your code in a function, and call that function from <body onload="newFunction();">
  • If you can use jQuery, you can wrap the code in $(function() { ... });
  • (正如 Kendall 所评论的)您可以将脚本移动到 <body>
  • 你可以把你的代码放在一个函数中,然后从 <body onload="newFunction();">
  • 如果可以使用jQuery,则可以将代码包装在 $(function() { ... });