![](/img/trans.png)
[英]How can I keep track of and display the amount of times a button has been clicked in total by all users?
[英]Change text of button by the amount of times it has been clicked
为了进行实践测试,我被要求找到一种方法来使按钮显示段落中的文本。 每次按下时,文本都必须更改。
第一次按下该按钮应该说“您按下了按钮”,第二次则是“第三次到第五次再次按下了它”(按3到5)(第六次),第六次以后应该说“停止! “
编辑编辑
这是完整的原始HTML,我不确定是否需要,但是html可能与大家都给我的javascript代码有关,对我不起作用。
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;
}
我应该怎么做才能使这项工作?
使用switch
语句来避免嵌套if
语句...
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;
}
}
还是这个呢?
'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);
您可以这样做:
'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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.