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

如何为我的示例代码应用合适的事件处理甚至事件委托机制?

问题修复方案

原始代码问题定位

你代码的核心错误是:事件监听器的回调函数接收的第一个参数是事件对象(Event),而非你预期的被点击DOM元素,所以你直接访问obj.style是取不到对应元素的样式属性的,自然无法实现切换效果。

修复方案1:调整现有事件处理逻辑

只需要修改changeColor函数,从事件对象中拿到绑定事件的DOM元素即可:

const hours=document.getElementById('hours');
const minutes=document.getElementById('minutes');
const seconds=document.getElementById('seconds');

hours.addEventListener('click',changeColor);
minutes.addEventListener('click', changeColor);
seconds.addEventListener('click', changeColor);

function changeColor(e){
    // e.currentTarget就是绑定了当前点击事件的DOM元素
    const targetEl = e.currentTarget;
    if(targetEl.style.backgroundColor==='seashell'){
        targetEl.style.backgroundColor='red';
    } else{
        targetEl.style.backgroundColor='seashell';
    }
}

修复方案2:使用事件委托优化逻辑

如果这三个div有共同的父元素,推荐用事件委托实现,不用单独给每个元素绑定事件,后续新增同类元素也不用重新绑定:
假设三个div的父元素id为time-container,代码如下:

// 只需要给父元素绑定一次事件
document.getElementById('time-container').addEventListener('click', changeColor);

function changeColor(e){
    // 判断点击的元素是不是三个目标div之一
    const targetEl = e.target;
    if(['hours', 'minutes', 'seconds'].includes(targetEl.id)){
        if(targetEl.style.backgroundColor==='seashell'){
            targetEl.style.backgroundColor='red';
        } else{
            targetEl.style.backgroundColor='seashell';
        }
    }
}

补充提示:如果你初始的背景色是通过CSS类设置的、不是行内样式,那style.backgroundColor是取不到对应值的,这种情况更推荐切换CSS类实现效果,可维护性更高:

.bg-seashell { background-color: seashell; }
.bg-red { background-color: red; }

逻辑里直接切换类即可:

targetEl.classList.toggle('bg-red');
targetEl.classList.toggle('bg-seashell');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:57:01