简体   繁体   English

即使单击两次按钮,如何使 function 仅工作一次?

[英]How to make function work only once even when button is clicked twice?

OK, guys.好了朋友们。 I am trying to create a tip calculator, and I came across some problems.我正在尝试创建一个小费计算器,但遇到了一些问题。 The thing is when the user enters a value, the program will ask(disabling the enter button) if the user wants to include the tip, so the user chooses yes or no.问题是当用户输入一个值时,程序会询问(禁用输入按钮)用户是否想要包含提示,因此用户选择是或否。 If either is chosen, the previous question disappears and the text appears "Tip is included" or "Tip is not included".如果选择其中任何一个,前一个问题就会消失,并出现“包含提示”或“不包含提示”的文本。 Now, if the user wants to edit the value above, the button will get enabled again but if it clicked one, it will again ask whether the user wants to include the tip.现在,如果用户想要编辑上面的值,按钮将再次启用,但如果它单击一个,它将再次询问用户是否想要包含提示。 SO my question is how can I make it so that no matter how many times that button is clicked, that function(asking tip) works only once?所以我的问题是如何做到这一点,以便无论单击该按钮多少次,该功能(询问提示)只能工作一次?

Here is some code, HTML这是一些代码,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: 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
}

You can define a global variable (flag) above the askForTip function and can set that toggle that flag on the first execution of askForTip and next while executing askForTip, you can check whether to stop or execute code depending upon the flag.您可以在 askForTip function 上方定义一个全局变量(标志),并可以在第一次执行 askForTip 和下一次执行 askForTip 时设置该标志,您可以根据标志检查是否停止或执行代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM