问题
For a practice test I am asked to find a way to make a button reveal text in a paragraph. Each time it is pressed, the text must change.
For the first time pressed the button should say "you pressed the button" second "you pressed it again third to fifth time "you pressed the button (a number from 3 to 5) times" and sixth and onward it should say "stop!"
EDIT EDIT EDIT
This is the entire Original HTML, i am not sure if it is needed, but maybe the html could have something to do with the javascript codes you all have given me to not work for me.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="q2.js" type="text/javascript"></script>
</head>
<body>
<button type="button" onclick="go()">ClickMe</button>
<p id="output">
</p>
</body>
</html>
JavaScript
function go() {
var out = document.getElementById("output");
var x = "hi there";
out.innerHTML = x;
}
What should I do to make this work?
回答1:
use a switch
statement to avoid nested if
statements...
var testCount = 0;
var out = document.getElementById("output");
function go(){
testCount++;
switch (testCount) {
case 1:
out.innerHTML = 'you pressed the button';
break;
case 2:
out.innerHTML = 'you pressed it again';
break;
case 3:
case 4:
case 5:
out.innerHTML = 'you pressed the button ' + testCount + ' times';
break;
default:
out.innerHTML = 'stop!!';
break;
}
}
回答2:
Or how about this one?
'use strict';
let count = 0;
// define this outside of function so it won't be defined over and over
let out = document.getElementById('output');
let message;
function go(e){
e.preventDefault();
count ++;
out.innerHTML = count > 1 ? count === 2 ? 'You pressed the button again!' : count > 1 && count < 6 ? `You pressed the button ${count} times!` : 'Stop!' : 'You pressed the button';
}
// It's best practice to stay away from inline JS, you could define your click handler in your script block
// For the following to work add id="btn1" to your button and remove the onclick handler
document.getElementById('btn1').addEventListener('click', go);
回答3:
You could do this:
'use strict';
let count = 0;
// define this outside of function so it won't be defined over and over
let out = document.getElementById('output');
let message;
function go(e){
e.preventDefault();
count ++;
if(count === 1) message = 'You pressed the button!';
if(count === 2) message = 'You pressed the button again';
if(count > 1 && count < 6) message = `You pressed the button ${count} times!`;
if(count >= 6) message = 'Stop!';
out.innerHTML = message;
}
// It's best practice to stay away from inline JS, you could define your click handler in your script block
// For the following to work add id="btn1" to your button and remove the onclick handler
document.getElementById('btn1').addEventListener('click', go);
来源:https://stackoverflow.com/questions/33091270/change-text-of-button-by-the-amount-of-times-it-has-been-clicked