简体   繁体   中英

How to push back the button on javascript?

I start to learn javascript from W3scholl . I wanna make the push button from this tutorial :

<html>
<body>

<h1>My First JavaScript</h1>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html> 

I want to clear the date text after I push the button again, how to do this?

You could add a new button like this:

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">
 Click me to display Date and Time.
</button>

<button type="button" onclick="Empty()">
 Click me to delete Date and Time.
</button>

<script>
function Empty(){
document.getElementById('demo').innerHTML = "";
}
</script>

<p id="demo"></p>

</body>
</html> 

You could introduce a global variable state and save the last changed state.

Click on button calls toggle and the function evaluates state for the next action. At the end of the function state changes with the logical NOT ! .

 function toggle() { if (state) { // check state document.getElementById('demo').innerHTML = ''; document.getElementById('button1').innerHTML = 'Click me to display Date and Time.' } else { document.getElementById('demo').innerHTML = Date(); document.getElementById('button1').innerHTML = 'Delete Date and Time.' } state = !state; // toggle state } var state; // undefined, becomes later true and false
 <button id="button1" type="button" onclick="toggle()">Click me to display Date and Time.</button> <p id="demo"></p>

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