【问题标题】:Value disappears after click event [duplicate]单击事件后值消失[重复]
【发布时间】:2023-04-04 13:10:01
【问题描述】:

我尝试使用带有 onclick 事件的 javascript 制作计算器,我希望按钮的值转换输入文本框。 当我在文本框中简单地编写代码时按钮的值,但它立即消失了。

我使用的代码你能在本文下面找到吗,我做错了什么。
HTML:

    var iGetal = 0;
    function GetalRekenmachine()
    {
        iGetal = iGetal + 1;
        document.getElementById("Display").value = iGetal;
    }
 <button id="Cijfer7" value="7" onclick="GetalRekenmachine()">7</button>
    <input type="text" id="Display"/>
    


    

【问题讨论】:

  • 页面刷新了吗?

标签: javascript onclick


【解决方案1】:

因为按钮的默认类型是提交。所以要么取消点击动作,要么将类型设置为按钮。

<button id="Cijfer7" value="7" onclick="GetalRekenmachine(); return false;">7</button>

<button type="button" id="Cijfer7" value="7" onclick="GetalRekenmachine()">7</button>

【讨论】:

  • epascarello 是对的。默认情况下,该按钮将是提交按钮。点击它会提交并刷新页面
  • 感谢您的帮助!
【解决方案2】:

var iGetal = 0;
    function GetalRekenmachine(event)
    {
        iGetal = iGetal + 1;
        document.getElementById("Display").value = iGetal;
        event.preventDefault()
    }
<button id="Cijfer7" value="7" onclick="GetalRekenmachine()">7</button>
    <input type="text" id="Display"/>

【讨论】:

    猜你喜欢
    • 2020-02-20
    • 2017-03-23
    • 2017-09-19
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    相关资源
    最近更新 更多