簡體   English   中英

即使單擊兩次按鈕,如何使 function 僅工作一次?

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

好了朋友們。 我正在嘗試創建一個小費計算器,但遇到了一些問題。 問題是當用戶輸入一個值時,程序會詢問(禁用輸入按鈕)用戶是否想要包含提示,因此用戶選擇是或否。 如果選擇其中任何一個,前一個問題就會消失,並出現“包含提示”或“不包含提示”的文本。 現在,如果用戶想要編輯上面的值,按鈕將再次啟用,但如果它單擊一個,它將再次詢問用戶是否想要包含提示。 所以我的問題是如何做到這一點,以便無論單擊該按鈕多少次,該功能(詢問提示)只能工作一次?

這是一些代碼,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
}

您可以在 askForTip function 上方定義一個全局變量(標志),並可以在第一次執行 askForTip 和下一次執行 askForTip 時設置該標志,您可以根據標志檢查是否停止或執行代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM