【问题标题】:How to make function work only once even when button is clicked twice?即使单击两次按钮,如何使功能仅工作一次?
【发布时间】:2021-03-14 15:01:27
【问题描述】:

好的,伙计们。我正在尝试创建一个小费计算器,但遇到了一些问题。问题是当用户输入一个值时,程序会询问(禁用输入按钮)用户是否想要包含提示,因此用户选择是或否。如果选择其中任何一个,前一个问题就会消失,并显示“包含提示”或“不包含提示”的文本。现在,如果用户想要编辑上面的值,按钮将再次启用,但如果它单击一个,它将再次询问用户是否想要包含提示。所以我的问题是我怎样才能做到这一点,无论该按钮被点击多少次,该功能(询问提示)只能工作一次?

这是一些代码,HTML

<h3>What is the bill?</h3>
<input type="number" id="bill" autocomplete="off">
<button id="enterTheBill">Enter</button>
<div id="askTip">
    <h3> Would you like to include the tip?</h3>
    <button id="yesTip">Yes</button>
    <button id="noTip">No</button>
</div>
<h3 id="includedTip">*Tip is included*</h3>
<h3 id="excludedTip">*Tip is NOT included*</h3>

Javascript:

document.getElementById('enterTheBill').onclick = askForTip
function askForTip() {
    document.getElementById('askTip').style.display = 'block'
    document.getElementById('enterTheBill').disabled = true
}

document.querySelector('#bill').onchange = enableButton
function enableButton() {
    document.getElementById('enterTheBill').disabled = false
}

【问题讨论】:

  • 使用变量。
  • 您可以使用变量作为标志。
  • 您是否可以访问任何库,例如 jQuery/underscore?

标签: javascript html function onclick


【解决方案1】:

您可以在 askForTip 函数上方定义一个全局变量(标志),并可以在第一次执行 askForTip 和下一次执行 askForTip 时设置切换该标志,您可以根据标志检查是否停止或执行代码。

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    相关资源
    最近更新 更多