javascript - addEventListener 不工作和一些问题

标签 javascript html dom dom-events addeventlistener

我应该根据我按的键[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>

最佳答案

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

window document 是不同的对象并且具有不同的事件,因此您应该根据您实际需要执行的操作将事件绑定(bind)到其中一个或另一个。

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

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

    我认为这没有什么区别。

  • onblur :由于该事件不会冒泡,因此您只能在特定事件上监听它。

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

    如果您在特定元素上监听它,假设是 <input>元素,那么当该输入失去焦点时它将被触发。

    从概念上讲,至少对我来说,考虑监听 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 => { ... }; 之后即可,像这样:

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>

关于javascript - addEventListener 不工作和一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45467003/

相关文章:

javascript - 如何将 HTML div 排列成一行,如结构?

javascript - 你如何在javascript上放置一个可变日期?

javascript - 如何将var添加到href

javascript - 如何排序和过滤 ngTable 日期(毫秒)数据?

php - 如何在按下按钮时执行脚本(并最终转移到另一个 URL)?

html - 如何使用 CSS 组合显式换行符和对齐文本

javascript - 如果我通过 ajax 响应附加所有 html 数据,这是一个好习惯吗?

javascript - &lt;input type ="time"step ="1"> 在 Chromium 的 .value 中不返回秒数

javascript - jQuery .on() 问题,console.log() 有效,但元素交互不起作用

javascript - SVG 元素在变换后丢失事件监听器