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

为何我的所有鼠标事件(mouseEvent)均无法正常工作?

问题分析与修复

核心问题

你代码里的事件绑定写法完全错误:

hello.addEventListener('click', disappear(hello));

这里disappear(hello)是直接执行函数,页面一加载就会把hello隐藏,而且事件监听实际绑定的是函数的返回值(undefined),导致点击事件根本不会触发任何操作。

修复方案

先修正事件绑定的正确写法,再优化切换逻辑,实现每次触发事件时隐藏当前短语、显示下一个,循环往复:

修正后的代码

HTML(保持结构,建议初始仅显示第一个按钮)
<div class="hello-world">
  <button id="hello"> Hello, World! </button>
  <button id="ciao" style="display: none;"> Ciao, Mondo!</button>
  <button id="hola" style="display: none;"> Hola, Mundo!</button>
  <button id="bonjour" style="display: none;"> Bonjour le monde!</button>
</div>
JavaScript
// 将所有短语元素存入数组,简化遍历与切换逻辑
const phrases = [
  document.getElementById("hello"),
  document.getElementById("ciao"),
  document.getElementById("hola"),
  document.getElementById("bonjour")
];

// 为每个元素绑定事件(这里用click,换成mouseover等事件直接改字符串即可)
phrases.forEach((phrase, index) => {
  phrase.addEventListener('click', () => {
    // 隐藏当前元素
    phrase.style.display = 'none';
    // 计算下一个元素的索引,通过取模实现循环切换
    const nextIndex = (index + 1) % phrases.length;
    // 显示下一个元素
    phrases[nextIndex].style.display = 'block';
  });
});

优化说明

  • 用数组统一管理元素,避免重复编写大量重复的事件绑定代码,逻辑更简洁
  • 事件监听传入的是匿名函数,只有触发事件时才会执行隐藏/显示操作
  • 取模运算(index + 1) % phrases.length实现循环切换,点击最后一个元素会自动回到第一个

内容的提问来源于stack exchange,提问作者Dayna-Marie Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:57:23