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

移除元素onclick后仍触发函数?剪刀石头布游戏交互异常求助

剪刀石头布游戏移除/恢复点击事件失效问题解决

问题根源

你代码失效的核心原因是:HTML中的img标签使用了内联onclick="Play(this)"属性,这种内联事件和通过JS.onclick赋值的事件不是同一套机制——你用gestures[i].onclick = null只能清除JS绑定的事件,内联的onclick依然会在点击时触发Play函数,所以看起来移除操作没生效。

解决方案

方案一:统一用JS绑定事件(推荐)

这种方式能让事件管理更统一,避免内联和JS绑定的冲突:

  1. 先删除HTML中所有img标签的onclick="Play(this)"属性:
<div class="type">
    <h2>Rock</h2>
    <img class="gesture" src="rock.png" id="rock" alt="Rock" width="250px" height="250px">
</div>
<div class="type">
    <h2>Paper</h2>
    <div class="wrapper">
        <img class="gesture" src="paper.png" id="paper" alt="Paper" width="200px" height="200px">
    </div>
</div>
<div class="type">
    <h2>Scissors</h2>
    <img class="gesture" src="scissors.png" id="scissors" alt="Scissors" width="250px" height="250px">
</div>
  1. 修改JS代码,统一初始化绑定事件,并在Play函数中移除/恢复:
const gestures = document.querySelectorAll('.gesture');

// 封装绑定事件的函数
function bindGestureClicks() {
    gestures.forEach(gesture => {
        gesture.onclick = function() {
            Play(this);
        };
    });
}

// 页面加载完成后绑定初始事件
bindGestureClicks();

function Play(selectedGesture) {
    // 移除所有手势的点击事件
    gestures.forEach(gesture => {
        gesture.onclick = null;
    });

    // 这里写你的机器人随机手势生成、胜负判断等逻辑...

    // 5秒后恢复点击事件
    setTimeout(bindGestureClicks, 5000);
}

方案二:保留内联事件,通过禁用元素实现(更简单)

如果不想修改HTML,可以直接禁用元素来阻止点击,比移除事件更直接:

function Play(selectedGesture) {
    const gestures = document.querySelectorAll('.gesture');
    
    // 禁用所有手势,添加视觉提示
    gestures.forEach(gesture => {
        gesture.style.opacity = '0.5';
        gesture.style.pointerEvents = 'none'; // 直接阻止点击事件触发
    });

    // 机器人逻辑...

    // 5秒后恢复可点击状态
    setTimeout(() => {
        gestures.forEach(gesture => {
            gesture.style.opacity = '1';
            gesture.style.pointerEvents = 'auto';
        });
    }, 5000);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:02:51