Button.onclick 会自动触发,然后不会再次触发

Button.onclick automatically triggers, then will not trigger again

本文关键字:然后 Button onclick      更新时间:2023-09-26

我有一个脚本,我用它来尝试一次只显示网页的一个部分。

function showMe(id){ clearPage(); changeDisplay(id, "block"); console.log(id)}

目前,我正在使用按钮来更改显示的部分。

var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=showMe("a-btn-section-id");
otherBtn.onclick=showMe("other-btn-section-id");

但是,当我加载页面时,会发生以下情况:

  1. 我看到附加到每个按钮的功能在控制台中依次激活一次。
  2. 页面拒绝响应进一步的按钮输入。

使用控制台进行测试表明 showMe() 及其调用的函数仍然都能正常工作。我确定我犯了一个非常基本的初学者错误(希望这就是为什么我在谷歌/搜索 StackOverflow/阅读事件处理文档时找不到这个问题的原因),但我对这个错误不知所措。为什么我的脚本会假设我的按钮在加载时被单击,为什么它不让我再次单击它们?

您正在调用函数,将值分配给onclick属性而不是附加函数,请尝试将onclick属性定义为:

aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};

尝试以下jsfiddle:

function showMe(id){ // some stuff..
  console.log(id)
}
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
<input type="button" value="a-btn" id="a-btn"/>
<input type="button" value="other-btn" id="other-btn"/>

希望这有帮助,