简体   繁体   中英

Starting a javascript prompt after a button is clicked

If I have a simple button in my html:

<button id="bgnBtn">Start Game</button>

and I want a prompt in my JS:

var userAdjective = prompt("Please provide an Adjective");

to initiate only after the button is clicked, how would I write this?

Can't seem to find this concept out there, at least for one so boiled down to basics like this.

Thanks,

Set an onclick handler for the button and then have it trigger a javascript function - note the use of the alert - just to show the functioning of the function:

 function promptMe(){ var userAdjective = prompt("Please provide an Adjective"); alert (userAdjective); }
 <button id="bgnBtn" onclick="promptMe()">Start Game</button>

I would recommend attaching an event listener to the button in your JS code.

document.querySelector('#bgnBtn').addEventListener('click', function() {
    var userAdjective = prompt("Please provide an Adjective");
    alert (userAdjective);
}

This example uses an anonymous function for handling the click event. You could also do the following:

document.querySelector('#bgnBtn').addEventListener('click', promptMe);

function promptMe() {
    var userAdjective = prompt("Please provide an Adjective");
    alert (userAdjective);
}

If you use an alert box it would look like this: Alert me

<script>
function myFunction() {
  alert("I am an alert box!");
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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