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

使用if-else语句时按钮首次点击无响应问题排查

问题分析与解决

问题现象

按钮首次点击无响应,第二次点击可正常跳转到目标页面。

问题原因

首次点击按钮时,触发的是authenticate()函数:

  • 当密码验证通过后,代码只是给按钮重新绑定了onclick事件,但本次点击已经执行完authenticate()的逻辑,不会触发刚绑定的跳转函数;
  • 第二次点击时,按钮的onclick事件已经被替换为跳转函数,因此可以正常触发跳转。

修复方案

验证通过后直接执行跳转逻辑,无需重新绑定点击事件,修改后的代码如下:

JavaScript代码

function authenticate() {
  let x = document.getElementById('aut').value;
  if (x == 'code') {
    // 验证通过直接跳转
    window.location.href = 'https://www.google.com';
  } else {
    alert('Please check your password')
  }
  console.log('If this message appears in the console, JavaScript is running.');
}

HTML代码

<div>
  <label for="auth">Password:</label>
  <input type="password" name="auth" id="aut">
  <button id="myButton" onclick="authenticate()">Authenticate</button>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:14:56