Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Button.onclick会自动触发,然后不会再次触发_Javascript_Html_Button_Onclick_Event Handling - Fatal编程技术网

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”);}