【问题标题】:addEventListener not working and a few questionsaddEventListener 不工作和几个问题
【发布时间】:2017-08-02 17:06:58
【问题描述】:

我应该根据我按 [RGBY] 的键来更改每个 div 的背景颜色。按 R 会使它们变为红色,按 G 变为绿色等。它现在不起作用,我不知道为什么。

除了主要问题,我还有一些其他问题:

首先,我应该在.addEventListener 上使用文档还是窗口来进行这个特定的练习?

第二,在document.addEventListener("keydown", switchColor)

里面

我应该这样做还是改用document.addEventListener("keydown", switchColor(e))?我对此感到困惑,因为我的switchColor 函数是这样构建的:const switchColor = e => {...}

    const divList = document.querySelectorAll("div");

    document.addEventListener("keydown", switchColor); // this or switchColor(e) ?
    //would 'window.addEventListener' be okay in here as well ??

    const switchColor = e => {
        let color = "n/a";
        switch (e.keyCode) {
            case 82: color = red; break; 
            case 89: color = yellow; break; 
            case 71: color = green; break; 
            case 66: color = blue; break; 
        }
        divList.forEach(value => {
            value.style.backgroundColor = color;
        });
    }
<body>
    <p>Press the R (red), Y (yellow), G (green) or B (blue) key to change paragraph colors accordingly.</p>

    <h1>Paragraph 1</h1>
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dignissim fringilla dapibus. Curabitur placerat efficitur
        molestie. Quisque quis consequat nibh. Aenean feugiat, eros eget aliquam vulputate, leo augue luctus lectus, non
        lobortis libero quam non sem. Aliquam sit amet tincidunt ex, mollis interdum massa.</div>

    <h1>Paragraph 2</h1>
    <div>Vivamus at justo blandit, ornare leo id, vehicula urna. Fusce sed felis eget magna viverra feugiat eget nec orci. Duis
        non massa nibh. Aenean vehicula velit a magna lobortis tempor ut quis felis. Proin vitae dui a eros facilisis fringilla
        ut ut ante.</div>

    <h1>Paragraph 3</h1>
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sit amet pharetra massa. Nulla blandit erat nulla, et scelerisque
        libero varius ut. Praesent bibendum eu magna ullamcorper venenatis. Sed ut pellentesque leo. Sed ultrices sapien
        consequat odio posuere gravida.</div>
</body>

</html>

【问题讨论】:

    标签: javascript html dom dom-events addeventlistener


    【解决方案1】:

    ? window.addEventListener(...) VS document.addEventListener(...):

    windowdocument 是不同的对象,具有不同的事件,因此您应该根据实际需要将事件绑定到其中一个或另一个。

    但是,有一些常见的选项,使用其中一个或另一个可能会有一些差异,尽管有时两个选项都可以模糊地使用而不会出现问题。例如:

    • onabort:当用户中止加载资源时调用,例如,当页面仍在加载时按下 chrome(导航栏左侧)上的 × 按钮。

      我认为这个没有区别。

    • onblur:由于该事件不冒泡,所以只能在特定事件上监听。

      因此,如果您在window 上侦听它,则当窗口本身失去焦点时(当用户切换到不同的选项卡时),您的事件侦听器将被调用。

      如果您在特定元素上监听它,比如&lt;input&gt; 元素,那么当该输入失去焦点时它将被触发。

      从概念上讲,至少对我来说,甚至想在document 上收听都是没有意义的。另外,如果你尝试一下,你会发现没有办法让它着火,至少在最新的 Chrome 中是这样:

      document.onblur = () => console.log('Triggered from document.');
      
    • onunload:当用户离开页面时调用。这个是window特有的。

    • ondrag:当drag 事件发生并且特定于document 时调用。

    这里是event handlers for window 的完整列表,这里是document 的完整列表。

    回到你的代码,你可以在其中的任何一个上收听keydown,但我想说最常见的事情是使用document,除非你有特定的原因,而是使用window,主要是该事件仅存在于window(如onunload)中,或者它们在一个和另一个中的工作方式存在差异,您确实需要在window(如onblur)上收听它。

    这样做的一个原因是传播的事件将在到达document 对象之前到达window 对象,尽管差异可以忽略不计。出于同样的原因,一般来说,您应该始终尝试尽可能靠近生成它们的元素来监听事件,以提高性能,尽管在某些情况下,您需要event delegation 以在需要处理的情况下提高性能以类似的方式在许多元素中创建一个事件并为每个元素创建一个侦听器将需要太多资源。

    因此,您应该使用它document.addEventListener('keydown', switchColor)

    ? ...('keydown', switchColor) VS ...('keydown', switchColor(e)):

    document.addEventListener 需要一个对 function 的引用,它将在每次发生正确事件时调用。因此,您需要在不带括号的情况下放置函数,否则您不会传递对它的引用,而是调用该函数时返回的任何内容,在您的情况下为 undefined

    此外,即使您没有注意到差异,该代码也已经有异味,因为您没有任何 e 变量来传递它,因此如果您尝试这样做,您将获得 ReferenceError .

    ? 修复你的代码:

    你的代码的问题是当你这样做时......

    document.addEventListener('keydown', switchColor)
    

    ...switchColor function 还没有定义,所以你也会在这里得到一个ReferenceError

    要修复它,只需将该行移到const switchColor = e =&gt; { ... }; 之后,如下所示:

    const divs = document.querySelectorAll('div');
    
    const switchColor = e => {
        let color = 'transparent';
    
        switch (e.keyCode) {
            case 82: color = 'red';     break; 
            case 89: color = 'yellow';  break; 
            case 71: color = 'green';   break; 
            case 66: color = 'blue';    break; 
        }
    
        divs.forEach(div => {
            div.style.backgroundColor = color;
        });
    };
    
    document.addEventListener('keydown', switchColor);
    <p>Press the R (red), Y (yellow), G (green) or B (blue) key to change paragraph colors accordingly.</p>
    
    <h1>Paragraph 1</h1>
    
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dignissim fringilla dapibus. Curabitur placerat efficitur molestie. Quisque quis consequat nibh. Aenean feugiat, eros eget aliquam vulputate, leo augue luctus lectus, non lobortis libero quam non sem. Aliquam sit amet tincidunt ex, mollis interdum massa.</div>
    
    <h1>Paragraph 2</h1>
    
    <div>Vivamus at justo blandit, ornare leo id, vehicula urna. Fusce sed felis eget magna viverra feugiat eget nec orci. Duis non massa nibh. Aenean vehicula velit a magna lobortis tempor ut quis felis. Proin vitae dui a eros facilisis fringilla ut ut ante.</div>
    
    <h1>Paragraph 3</h1>
    
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sit amet pharetra massa. Nulla blandit erat nulla, et scelerisque libero varius ut. Praesent bibendum eu magna ullamcorper venenatis. Sed ut pellentesque leo. Sed ultrices sapien consequat odio posuere gravida.</div>

    【讨论】:

    • @JDev 我添加了一些额外的细节,也许你想看看它们。
    【解决方案2】:

    使用前先定义switchColor。然后您需要使用红色、黄色等作为字符串,因此请将它们放在引号中。这似乎有效:

    <body>
        <p>Press the R (red), Y (yellow), G (green) or B (blue) key to change paragraph colors accordingly.</p>
    
        <h1>Paragraph 1</h1>
        <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dignissim fringilla dapibus. Curabitur placerat efficitur
            molestie. Quisque quis consequat nibh. Aenean feugiat, eros eget aliquam vulputate, leo augue luctus lectus, non
            lobortis libero quam non sem. Aliquam sit amet tincidunt ex, mollis interdum massa.</div>
    
        <h1>Paragraph 2</h1>
        <div>Vivamus at justo blandit, ornare leo id, vehicula urna. Fusce sed felis eget magna viverra feugiat eget nec orci. Duis
            non massa nibh. Aenean vehicula velit a magna lobortis tempor ut quis felis. Proin vitae dui a eros facilisis fringilla
            ut ut ante.</div>
    
        <h1>Paragraph 3</h1>
        <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sit amet pharetra massa. Nulla blandit erat nulla, et scelerisque
            libero varius ut. Praesent bibendum eu magna ullamcorper venenatis. Sed ut pellentesque leo. Sed ultrices sapien
            consequat odio posuere gravida.</div>
    </body>
    <script>
        const divList = document.querySelectorAll("div");
    
        const switchColor = e => {
            let color = "n/a";
            switch (e.keyCode) {
                case 82: color = 'red'; break; 
                case 89: color = 'yellow'; break; 
                case 71: color = 'green'; break; 
                case 66: color = 'blue'; break; 
            }
            divList.forEach(value => {
                value.style.backgroundColor = color;
            });
        }
    
        document.addEventListener("keydown", switchColor); // this or switchColor(e) ?
        //would 'window.addEventListener' be okay in here as well ??
    </script>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2012-08-31
      • 2011-06-14
      • 2012-07-10
      • 1970-01-01
      相关资源
      最近更新 更多