Javascript Button.onclick会自动触发,然后不会再次触发
我有一个脚本,我正在使用它尝试一次只显示网页的一个部分Javascript Button.onclick会自动触发,然后不会再次触发,javascript,html,button,onclick,event-handling,Javascript,Html,Button,Onclick,Event Handling,我有一个脚本,我正在使用它尝试一次只显示网页的一个部分 函数showMe(id){clearPage();changesplay(id,“block”);console.log(id)} 目前,我正在使用按钮更改显示的部分 var aBtn = document.getElementById("a-btn"); var otherBtn = document.getElementById("other-btn"); aBtn.onclick=showMe("a-btn-section-id");
函数showMe(id){clearPage();changesplay(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");
但是,当我加载页面时,会发生以下情况:
使用控制台进行测试表明showMe()及其调用的函数仍能正常工作。我确信我犯了一个非常基本的初学者错误(希望这就是为什么我在Google/search StackOverflow/read event handling docs时找不到这个问题的原因),但我不知道这个错误是什么。为什么我的脚本会假设我的按钮在加载时被单击,为什么不让我再次单击它们?您正在调用函数并将值分配给
onclick
属性,而不是附加函数,请尝试将onclick
属性定义为:
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
尝试以下JSFIDLE:
函数showMe(id){//一些东西。。
控制台日志(id)
}
var aBtn=document.getElementById(“a-btn”);
var otherBtn=document.getElementById(“其他btn”);
aBtn.onclick=function(){showMe(“a-btn-section-id”);};
otherBtn.onclick=function(){showMe(“其他btn节id”);}代码>