Once upon a time I wrote an application that plays a point with a user. At the same time, constructions like

if (confirm(`Не желаете ли кон в 21?`)) { alert( `Атлична!` ); playGame(); } 

or

 bet = prompt(`Назначьте Вашу ставку.`, ''); 

Now I decided to refactor this case and get rid of modal operators. Well, for the alert, I created the function sendMessage (message), which places the necessary text in the appropriate window. But with the other operators more difficult. Made this piece of markup:

 <form> <label> Ваш ответ: <input type="text" name="myForm"> </label> <br> <div class="buttons"> <input class="myButton sendButton" value="Отправить" type="button"> <input class="myButton yesButton" value="Да" type="button"> <input class="myButton noButton" value="Нет" type="button"> </div> </form> 

Made such a handler:

 let buttonsBlock = document.body.querySelector(`.buttons`); let input = document.body.querySelector(`input[type="text"]`); buttonsBlock.addEventListener('click', buttonsBlockHandler); function buttonsBlockHandler() { if (event.target.classList.contains(`yesButton`)) { return true; } if (event.target.classList.contains(`noButton`)) { return false; } if (event.target.classList.contains(`sendButton`)) { let answer = input.value; input.value = ``; return answer; } } 

But then I realized that if I rewrite the first fragment like this:

 sendMessage(`Не желаете ли кон в 21?`); if (buttonsBlockHandler()) {} 

then buttonsBlockHandler is simply executed without pressing the button, and the target will not be defined. There was also a thought in each block of code to override the handler. Something like that:

 ... buttonsBlockHandler = function() { if (event.target.classList.contains(`yesButton`)) { playGame(); ... sendMessage(`Не желаете ли кон в 21?`); ... buttonsBlockHandler = function() { if (event.target.classList.contains(`yesButton`)) { takeTheCard(); ... sendMessage(`Еще карту?`); ... 

But this, damn it, a perversion of some kind. Can you please tell me how to wait for the button to be pressed?

    1 answer 1

    Try jQuery, there is a method .submit Then your code will look something like this

     $(".yesButton").submit(playGame()) 

    Fixed

    • one
      the function will start immediately - before the click, for obvious reasons. - NeedHate
    • try submit and why minus immediately?) $ (". yesButton"). submit (playGame ()) - Maxim Stikharev
    • one
      Once again - the function will be executed immediately ... but if there is: $ (". YesButton"). Submit (playGame), then there is a chance that this will work as intended. Right? - NeedHate
    • Yes, submit goes. When the person released the button and left the request. - Maxim Stikharev