【问题标题】:Button.onclick automatically triggers, then will not trigger againButton.onclick 自动触发,以后不会再触发
【发布时间】:2015-01-28 21:45:14
【问题描述】:

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

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/阅读事件处理文档时找不到这个问题的原因),但我不知道什么那个错误是。为什么我的脚本会假设我的按钮在加载时被点击,为什么它不允许我再次点击它们?

【问题讨论】:

    标签: javascript html button onclick event-handling


    【解决方案1】:

    您正在调用该函数并将值分配给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"/>

    希望这会有所帮助,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 2012-03-05
      • 2019-08-10
      相关资源
      最近更新 更多