You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套addEventListener中箭头函数与普通函数的点击行为差异原因

事件绑定问题解析

代码示例

JavaScript 代码

document.addEventListener("DOMContentLoaded", function() {
  // Scenario 1 
  const btn = document.querySelector(".test");
  btn.addEventListener("click", () => {
    const fragment = document.createDocumentFragment();
    var x = document.createElement('p');
    x.className = "di";
    x.style.background = "aqua";
    for (var i = 1; i < 5; i++) {
      x.textContent = ' Change background color for ' + `${i}` + " element";
      x.id = 'para' + `${i}`;
      fragment.append(x.cloneNode(true));
    }
    document.body.append(fragment);
    //Nested addeventlistener
    document.getElementById("para1").addEventListener("click", () => {
      para1.style.background = "yellow"
    });
    document.getElementById("para2").addEventListener("click", () => {
      para2.style.background = "yellow"
    });

    function changeBackgroundColor(elem) {
      elem.style.background = "yellow";
    }
        //Nested addeventlistener

    document.getElementById("para3").addEventListener("click", changeBackgroundColor(para3));
    document.getElementById("para4").addEventListener("click", changeBackgroundColor(para4));
  });
});

HTML 代码

<button class="test">create 4 elements</button>

操作步骤与观察

  • 步骤1:点击HTML按钮「create 4 elements」,创建4个<p>元素。
  • 观察1:第1、2个使用箭头函数绑定click事件的<p>元素,需手动点击才能将背景色从aqua变为yellow。
  • 观察2:第3、4个未使用箭头函数的<p>元素,无需点击就默认变为yellow。

问题解析

第3、4个元素的click事件完全无效,核心原因是事件绑定的写法错误:
addEventListener的第二个参数要求传入函数引用,但此处写的changeBackgroundColor(para3)是直接调用函数,会立即执行该代码,导致元素背景色瞬间变成yellow。同时因为changeBackgroundColor函数没有返回值(默认返回undefined),相当于给click事件绑定了undefined,后续点击这两个元素时,不会触发任何操作。

如果要让这两个元素的点击事件生效,需要传递函数引用,可通过以下两种方式修正:

// 方式1:通过事件对象获取目标元素
document.getElementById("para3").addEventListener("click", function() {
  changeBackgroundColor(this);
});
// 方式2:用箭头函数包裹延迟执行
document.getElementById("para4").addEventListener("click", () => changeBackgroundColor(para4));

内容的提问来源于stack exchange,提问作者Richard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:05:23