使用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
相关产品推荐
相关产品推荐

